Python: 如何漂亮地显示json结果?

Python: How to display json results nicely?

我目前正在构建一个 Telegram 机器人,并在 Google 地点 API 到 return 附近的用户位置上获得 JSON 响应。 我得到的 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

请帮忙。

可能与:

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

你想要 json 格式吗? 然后你可以这样做:

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

如果您只需要字符串列表:

lines = [f"{s['name']}: {s['rating']}" for s in object_json['results']]

或者您只想打印:

for s in object_json['results']:
    print(f"{s['name']}: {s['rating']}")

您需要 3.6 或更高版本的 python 解释器才能使用 f-string(f"...")。
我你不知道,替换 f"{s['name']}: {s['rating']}" -> '{name}: {rating}'.format(**s)