You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:如何优雅格式化展示JSON结果?Telegram Bot场景求助

如何将Google Places API结果格式化为指定的字符串格式?

我正在开发一款Telegram Bot,调用Google Places API获取附近地点后,得到的JSON响应结构如下:

{
  "results": [
    {
      "name": "Golden Village Tiong Bahru",
      "opening_hours": {"open_now": true},
      "rating": 4.2,
      "types": ["movie_theater", "point_of_interest", "establishment"],
      "user_ratings_total": 773
    },
    {
      "name": "Cathay Cineplex Cineleisure Orchard",
      "opening_hours": {"open_now": true},
      "rating": 4.2,
      "types": ["movie_theater", "point_of_interest", "establishment"],
      "user_ratings_total": 574
    }
  ]
}

我当前用这段代码提取字段:

json.dumps([[s['name'], s['rating']] for s in object_json['results']], indent=3)

得到的输出是嵌套列表格式:

[
   [ "Golden Village Tiong Bahru", 4.2 ],
   [ "Cathay Cineplex Cineleisure Orchard", 4.2 ]
]

但我希望把结果展示成这样的字符串格式:Golden Village Tiong Bahru : 4.2, Cathay Cineplex Cineleisure Orchard : 4.2,请问该怎么修改代码?


解决方案

你可以用字符串格式化结合str.join()方法来实现这个需求,具体代码如下:

# 遍历每个结果,拼接成"名称 : 评分"的字符串
formatted_items = [f"{item['name']} : {item['rating']}" for item in object_json['results']]
# 用逗号加空格把所有字符串连接起来
final_output = ', '.join(formatted_items)

print(final_output)

运行这段代码后,就能得到你想要的输出:

Golden Village Tiong Bahru : 4.2, Cathay Cineplex Cineleisure Orchard : 4.2

额外优化:处理缺失评分的情况

如果API返回的结果中可能存在没有rating字段的地点(比如新开业的商家),可以用dict.get()方法设置默认值,避免报错:

formatted_items = [f"{item['name']} : {item.get('rating', '暂无评分')}" for item in object_json['results']]
final_output = ', '.join(formatted_items)

这样遇到没有评分的地点时,会显示名称 : 暂无评分,让你的Bot更健壮。

内容的提问来源于stack exchange,提问作者blueKingdom11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 19:48:14