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

问题描述 投票:0回答:3

我目前正在构建一个Telegram Bot,并在Google Places API上获得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

请帮助。

python json python-telegram-bot
3个回答
1
投票

您是否想要json格式?然后,您可以执行以下操作:

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

0
投票

也许与:

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

0
投票

很简单

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

for item in items:
    print('{} : {}'.format(item[0],item[1]))
© www.soinside.com 2019 - 2024. All rights reserved.