首页 > 解决方案 > 在 Python 中正确引用 JSON。字符串与整数和嵌套项

问题描述

下面的示例 JSON 文件

{
   "destination_addresses" : [ "New York, NY, USA" ],
   "origin_addresses" : [ "Washington, DC, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "225 mi",
                  "value" : 361715
               },
               "duration" : {
                  "text" : "3 hours 49 mins",
                  "value" : 13725
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

我希望参考距离和持续时间的文本值。我已经做了研究,但我仍然不确定我做错了什么......

我有一个使用几行代码的工作,但我正在寻找一个干净的单行解决方案..

感谢您的帮助!

标签: pythonjsonnested

解决方案


如果您使用的是常规 JSON 模块:

import json

你正在像这样打开你的 JSON:

json_data = open("my_json.json").read()
data      = json.loads(json_data)

# Equivalent to:
data      = json.load(open("my_json.json"))

# Notice json.load vs. json.loads

那么这应该做你想要的:

distance_text, duration_text = [data['rows'][0]['elements'][0][key]['text'] for key in ['distance', 'duration']]

希望这是你想要的!


推荐阅读