Home > Mobile >  TypeError while trying to parse value from json
TypeError while trying to parse value from json

Time:11-18

I have this Json (and the ... at the middle of the code it's to reduce the amount of Json in this question, the full Json is in here https://pastebin.com/acKCSq8D):

[
  {
    "columnHeader": {
      "dimensions": [
        "ga:city"
      ],
      "metricHeader": {
        "metricHeaderEntries": [
          {
            "name": "ga:users",
            "type": "INTEGER"
          }
        ]
      }
    },
    "data": {
      "rows": [
        {
          "dimensions": [
            "(not set)"
          ],
          "metrics": [
            {
              "values": [
                "984"
              ]
            }
          ]
        },
        {
          "dimensions": [
            "Sao Paulo"
          ],
          "metrics": [
            {
              "values": [
                "555"
              ]
            }
          ]
        },
        ...
        {
          "dimensions": [
            "Xanxere"
          ],
          "metrics": [
            {
              "values": [
                "1"
              ]
            }
          ]
        }
      ],
      ...
    }
  }
]

And I'm trying to take the items "dimensions" and "values" but using this code:

import json
import pandas as pd

with open('test.json') as f:
    raw_json = json.load(f)

for i in raw_json:
        print(i['data']['rows']['dimensions'])

I'm getting this error:

Traceback (most recent call last):
  File "C:\Users\gusta\Desktop\Projects\papai\test.py", line 10, in <module>
    print(i['data']['rows']['dimensions'])
TypeError: list indices must be integers or slices, not str

How could I extract such value as dimensions without returning such error?

CodePudding user response:

The rows interpreted as lists so that you need to loop through them as well to extract the dimensions. Here is a solution.

for i in raw_json:
    for j in i['data']['rows']:
        print(j['dimensions'])

CodePudding user response:

Your top level is a list not a dictionary. Try raw_json[0] to access your dict and go from there.

likewise "rows" accesses a list, you'll need to index in there rather than key-in.

CodePudding user response:

If you see the following type(i['data']['rows']) is list, hence you are getting TypeError

In [260]: for i in raw_json:
     ...:     print(type(i))
     ...:     print(type(i['data']))
     ...:     print(type(i['data']['rows']))
     ...:     for j in i['data']['rows']:
     ...:         # print(j['dimensions'])
     ...:         # print(type(j))
     ...:         pass
     ...:
<class 'dict'>
<class 'dict'>
<class 'list'>
  • Related