简体   繁体   English

如何从 Python 中的 JSON object 获取特定数据

[英]How to get specific data from JSON object in Python

I have a dict stored under the variable parsed :我在变量parsed下存储了一个字典:

{
    "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
    }
}

I am trying to get the "web" value from each JSON entry but can only get the key values.我正在尝试从每个 JSON 条目中获取“web”值,但只能获取键值。

for x in parsed:
     print(x["web"])

I tried doing this ^ but kept getting this error: "string indices must be integers".我尝试这样做 ^ 但不断收到此错误:“字符串索引必须是整数”。 Can somebody explain why this is wrong?有人可以解释为什么这是错误的吗?

A little information on your parsed data there: this is basically a dictionary of dictionaries.那里有一些关于你解析数据的信息:这基本上是一本字典。 I won't go into too much of the nitty gritty but it would do well to read up a bit on json : https://www.w3schools.com/python/python_json.asp我不会 go 过多的细节,但最好阅读一下jsonhttps_python://www.w3

In your example, for x in parsed is iterating through the keys of the parsed dictionary, eg 8119300029 , 8119300030 , etc. So x is a key (in this case, a string), not a dictionary.在您的示例中, for x in parsed正在遍历parsed字典的键,例如81193000298119300030等。因此x是键(在本例中为字符串),而不是字典。 The reason you're getting an error about not indexing with an integer is because you're trying to index a string -- for example x[0] would give you the first character 8 of the key 8119300029 .您收到有关未使用 integer 进行索引的错误的原因是因为您正在尝试对字符串进行索引 - 例如x[0]将为您提供键8119300029的第一个字符8

If you need to get each web value, then you need to access that key in the parsed[x] dictionary:如果您需要获取每个web值,则需要访问parsed[x]字典中的该键:

for x in parsed:
    print(parsed[x]["web"])

Output: Output:

4
2
0
...

because your x variable is dict key name因为你的 x 变量是 dict 键名

for x in parsed:
    print(parsed[x]['web'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM