i want print, python 'json' list, dictionary Importing mixed data
exam json data
{
"data": [
{
"rows": [
{
"dimensions": [
{
"value": "title1"
}
],
"metrics": [
{
"value": "potato"
},
{
"value": "sweetpotato"
},
{
"conversion_annotation_value": []
},
{
"value": "123123"
}
]
},
]
}
],
}
As far as I know, i use try
itemlist = json.loads(r.text)
for i in itemlist['data']['rows']['dimensions']:
...
for i in itemlist['data']['rows']['metrics']:
...
error, i was see
TypeError: list indices must be integers or slices, not str
i want see, this json data
'title1'
'123123'
CodePudding user response:
They are lists inside each dict. So you need to access them like list elements first:
for i in itemlist['data'][0]['rows'][0]['dimensions']:
print(i.get('value'))
for i in itemlist['data'][0]['rows'][0]['metrics']:
print(i.get('value'))
CodePudding user response:
Use itemlist['data']['rows'].get('dimensions', [])
instead using the .get()
property of a dict.
Or a bit more generally:
itemlist = json.loads(r.text)
for k, v in itemlist['data']['rows']:
for i in v:
if k == 'a':
# code ....
elif k == 'b':
# code ....
# ...