python - python解析json文件
问题描述
我是 python 和 json 的新手。我有一个下面的 json 文件,我需要在其中解析 json 文件中的“值”
{
"link": [
{
"attributes": [
{
"value": "backup",
"name": "name"
},
{
"value": "",
"name": "description"
}
],
},
{
"attributes": [
{
"value": "com.cap.blueprints",
"name": "name"
},
{
"value": "",
"name": "description"
}
],
}
],
}
我试过下面的代码。但我收到错误
with open ("respose_json.txt") as f2:
data=json.load(f2)
for x in data:
print(x['attributes']['value'])
error:
print(x['attributes']['value'])
TypeError: string indices must be integers
解决方案
- 您缺少最外层的
link
键。 - 属性包含属性列表,每个属性都有值。
尝试这样的事情:
import json
with open("respose_json.txt") as json_file:
data = json.loads(json_file)["link"]
for attributes in data:
for attribute in attributes['attributes']:
print(attribute['value'])
推荐阅读
- javascript - node.js和python中相同问题解决方案的不同结果
- javascript - 在套件脚本 2.0 中加载保存的搜索时 search.run().getRange 出错
- html - Chrome浏览器计算错误的元素宽度
- c# - GMap.NET 我怎样才能做出准确的路由?
- powershell - PowerShell获取包含IP地址的行并将所有这些行保存在另一个文件中
- c# - .Net core 3.x Keyless Entity Types 避免创建表
- shopify - 将元字段暴露给 Storefront API 错误
- javascript - 在反应应用程序中更改密码减速器(axios + redux + jwt + bcrypt)
- ios - uitabbar隐藏Applozic SDK时出现黑条
- java - 我在 ICU4J 库中得到错误的输出