I'm a python newbie and I need to read and manipulate elements from a json file, but I keep getting errors and I have no idea how to move forward. This is my code:
import json
with open('file.txt', 'r') as json_data:
d = json.load(json_data)
An example of the dataset:
[
{
'id': 1,
'name': 'a',
'city': 'Paris'
},
{
'id': 2,
'name': 'b',
'city': 'Mons'
},
{
'id': 3,
'name': 'c.',
'city': 'Leuven'
}
]
When I try to get only id or name, I get this error:
city = d['city']
TypeError Traceback (most recent call last)
in ()
----> 1 city = d['city']
TypeError: list indices must be integers or slices, not str
Then I tried this:
city = d[:]['city']
TypeError Traceback (most recent call last)
in () ----> 1 city = d[:]['city']
TypeError: list indices must be integers or slices, not str
Any ideas? Thanks!
city = d[0]['city']? Try looping instead - user2575725