Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeError while trying to parse value from json

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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'])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading