【问题标题】:Python: How to display json results nicely?Python:如何很好地显示 json 结果?
【发布时间】:2020-02-28 10:09:38
【问题描述】:

我目前正在构建一个 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

请帮忙。

【问题讨论】:

  • for s in object_json['results']: print('%(name)s : %(rating)s' % s).

标签: python json python-telegram-bot


【解决方案1】:

你想要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可以吗?只是文本因为我会有 " " 引号和一些奇怪的字符 \u2013 { "Park Hotel Alexandra": 4.3, "ibis budget Singapore Mount Faber (formerly known as Fragrance Hotel \u2013 Royal)": 3.6 }
  • 非常感谢您的帮助!!我尝试了 for 循环 它可以工作,但它只给了我第一个项目的名字。我也一直在尝试找出 for 循环。
  • 我刚刚意识到这可能是因为我使用 return 而不是 print
  • 您好只是想知道,如果在键值对中,值在列表中,是否可以删除下划线?现在我的结果是Local Restaurant & Bar:餐厅、食物、point_of_interest、场所。感谢您的帮助
  • @blueKingdom11 您可以为此调用str.replace 方法。例如,s['rating'].replace('_', ' ')
【解决方案2】:

也许有:

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

【讨论】:

    猜你喜欢
    • 2012-05-02
    • 1970-01-01
    • 2018-09-11
    • 2021-10-16
    • 2011-02-21
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    相关资源
    最近更新 更多