Tommy Tran
Tommy Tran

Reputation: 3

How to get specific data from JSON object in Python

I have a dict stored under the variable 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.

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?

Upvotes: 0

Views: 141

Answers (2)

Aelarion
Aelarion

Reputation: 417

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

In your example, for x in parsed is iterating through the keys of the parsed dictionary, e.g. 8119300029, 8119300030, etc. So x is a key (in this case, a string), not a dictionary. 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.

If you need to get each web value, then you need to access that key in the parsed[x] dictionary:

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

Output:

4
2
0
...

Upvotes: 1

Sean
Sean

Reputation: 86

because your x variable is dict key name

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

Upvotes: 1

Related Questions