Python:如何很好地显示json结果?

2024-06-01 01:41:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在构建一个电报机器人,并在GooglePlacesAPI上获得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

请帮忙


Tags: namejsonopenresultsratingopeninghoursorchard
2条回答

您想要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)

可能是:

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

相关问题 更多 >