如何在Python中从JSON对象获取特定数据
我有一个dict存储在变量如何在Python中从JSON对象获取特定数据,python,json,Python,Json,我有一个dict存储在变量下,已解析: { "8119300029": { "store": 4, "total": 4, "web": 4 }, "8119300030": { "store": 2, "total": 2, &qu
下,已解析:
{
"8119300029": {
"store": 4,
"total": 4,
"web": 4
},
"8119300030": {
"store": 2,
"total": 2,
"web": 2
},
"8119300031": {
"store": 0,
"total": 0,
"web": 0
},
"8119300032": {
"store": 1,
"total": 1,
"web": 1
},
"8119300033": {
"store": 0,
"total": 0,
"web": 0
},
"8119300034": {
"store": 2,
"total": 2,
"web": 2
},
"8119300036": {
"store": 0,
"total": 0,
"web": 0
},
"8119300037": {
"store": 0,
"total": 0,
"web": 0
},
"8119300038": {
"store": 2,
"total": 2,
"web": 2
},
"8119300039": {
"store": 3,
"total": 3,
"web": 3
},
"8119300040": {
"store": 3,
"total": 3,
"web": 3
},
"8119300041": {
"store": 0,
"total": 0,
"web": 0
}
}
我试图从每个JSON条目中获取“web”值,但只能获取键值
for x in parsed:
print(x["web"])
我尝试过这么做,但一直出现这样的错误:“字符串索引必须是整数”。有人能解释一下为什么这是错误的吗?这里有一些关于解析数据的信息:这基本上是一本字典词典。我不会深入讨论太多的细节,但最好读一下json
:
在您的示例中,解析的
中x的
正在迭代解析的字典的键,例如,8119300029
,8119300030
,等等。因此,x
是键(在本例中是字符串),而不是字典。不使用整数编制索引时出现错误的原因是,您试图为字符串编制索引,例如,x[0]
将为您提供键8119300029
的第一个字符8
如果需要获取每个web
值,则需要在parsed[x]
字典中访问该键:
for x in parsed:
print(parsed[x]["web"])
输出:
4
2
0
...
因为您的x变量是dict key name
for x in parsed:
print(parsed[x]['web'])
发布可以用Json执行的最少完整代码。您是否已将其从Json转换为python对象?