python : Get value from a list of Json dictionary

标签 python json list dictionary google-api

我需要从 google api 响应中获取值。 我的 json 响应如下:

direct =
[{ 
'summary': 'Jakarta Inner Ring Road/Jl. Pantura/Jl. Tol Pelabuhan', 
'legs': [{
          'duration': {'value': 2130, 'text': '36 mins'}, 
          'via_waypoint': [], 
          'start_address': 'North Jakarta, North Jakarta City, Special Capital Region of Jakarta, Indonesia', 
          'duration_in_traffic': {'value': 2475, 'text': '41 mins'}, 
          'end_address': 'West Jakarta, West Jakarta City, Special Capital Region of Jakarta, Indonesia', 
          'start_location': {'lat': -6.138709899999999, 'lng': 106.8640136}, 
          'distance': {'value': 17777, 'text': '17.8 km'}, 
          'traffic_speed_entry': [], 
          'end_location': {'lat': -6.168346199999999, 'lng': 106.7588346}
         }]
}]

我需要从获取持续时间距离

我尝试了多种方法,这是我的最后一个代码:

for who in direct:
    act_dist = (direct ["legs"][0]["distance"]["value"])
    act_time2 = (direct2 ["legs"][0]["duration"]["value"])

并收到此错误: *回溯(最近一次调用最后一次):

File "C:src/distance.py", line 34, in <module>
    act_dist = (direct ["legs"][0]["distance"]["value"])
TypeError: list indices must be integers or slices, not str*

谁能帮忙解决这个问题吗? 谢谢

最佳答案

你的代码实际上应该是:

for who in direct:
    act_dist = (who ["legs"][0]["distance"]["value"])
    act_time2 = (who ["legs"][0]["duration"]["value"])

关于 python : Get value from a list of Json dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41458125/

相关文章:

arrays - Ansible with_subelements 嵌套级别

java - 相对排序 - insertBefore() 和 insertAfter() 方法

python - 用 Pandas 过滤 CSV

android - 如何使用 Json(类别和子类别)在 Android fragment 中显示 GridView 图像

json - JSON 到 XML 的 XSLT 3.0 转换 — 数字数据类型

c# - XML 到 JSON - 将 Json 对象转换为 Json 数组

python - pygame中自制的2D碰撞检测不起作用

python - 融化 Pandas DataFrame

python - Pywinauto菜单选择错误-Wireshark

python - 无法导入设置 wsgi Django