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?
>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'])