python - 在 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"
}
我希望参考距离和持续时间的文本值。我已经做了研究,但我仍然不确定我做错了什么......
我有一个使用几行代码的工作,但我正在寻找一个干净的单行解决方案..
感谢您的帮助!
解决方案
如果您使用的是常规 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']]
希望这是你想要的!
推荐阅读
- wordpress - MAMP Pro:无法通过 URL 访问 WordPress 站点
- c# - Web.config 转换 - VS 扩展
- stm32 - 使用 STs I2C HAL 库不向寄存器写入数据
- laravel - 当不存在订阅时,Laravel 收银员`$user->subscribed()` 返回 true
- c# - C# 使用 Include 连接两个表。数据来自模型
- jhipster - 你如何配置 JHipster-JDL 不自动创建主键?
- kubernetes - 在 Python 中向 GKE master 进行身份验证
- mp4 - 微软文件接收器 Mpeg4
- css - 尝试使用 webpack 4 从 scss 文件中获取 css 文件
- javascript - 为什么在手动重新排序和恢复 dom 项目后,淘汰模板绑定停止工作?