Getting specific field values from Json Python

Viewed 15065

I have a JSON file, and what I am trying to do is getting this specific field '_id'. Problem is that when I use json.load('input_file'), it says that my variable data is a list, not a dictionary, so I can't do something like:

for value in data['_id']:
    print(data['_id'][i])

because I keep getting this error: TypeError: list indices must be integers or slices, not str

What I also tried to do is:

data = json.load(input_file)[0]

It kinda works. Now, my type is a dictionary, and I can access like this: data['_id'] But I only get the first '_id' from the archive...

So, what I would like to do is add all '_id' 's values into a list, to use later.

input_file = open('input_file.txt')
data = json.load(input_file)[0] 
print(data['_id'])# only shows me the first '_id' value

Thanks for the help!

[{
 "_id": "5436e3abbae478396759f0cf",
 "name": "ISIC_0000000",
 "updated": "2015-02-23T02:48:17.495000+00:00"
},
{
 "_id": "5436e3acbae478396759f0d1",
 "name": "ISIC_0000001",
 "updated": "2015-02-23T02:48:27.455000+00:00"
},
{

 "_id": "5436e3acbae478396759f0d3",
 "name": "ISIC_0000002",
 "updated": "2015-02-23T02:48:37.249000+00:00"
},
{
 "_id": "5436e3acbae478396759f0d5",
 "name": "ISIC_0000003",
 "updated": "2015-02-23T02:48:46.021000+00:00"
 }]
3 Answers

You want to print the _id of each element of your json list, so let's do it by simply iterating over the elements:

input_file = open('input_file.txt')
data = json.load(input_file)  # get the data list
for element in data:  # iterate on each element of the list
    # element is a dict
    id = element['_id']  # get the id
    print(id)  # print it

If you want to transform the list of elements into a list of ids for later use, you can use list comprehension:

ids = [ e['_id'] for e in data ]  # get id from each element and create a list of them

As you can see the data is a list of dictionaries

for looping over data you need to use the following code

for each in data:
    print each['_id']
    print each['name']
    print each['updated']

it says that my variable data is a list, not a dictionary, so I can't do something like:

for value in data['_id']:
     print(data['_id'][i])

Yes, but you can loop over all the dictionaries in your list and get the values for their '_id' keys. This can be done in a single line using list comprehension:

data = json.load(input_file)

ids = [value['_id'] for value in data]
print(ids)

['5436e3abbae478396759f0cf', '5436e3acbae478396759f0d1', '5436e3acbae478396759f0d3', '5436e3acbae478396759f0d5']

Another way to achieve this is using the map built-in function of python:

ids = map(lambda value: value['_id'], data)

This creates a function that returns the value of the key _id from a dictionary using a lambda expression and then returns a list with the return value from this function applied on every item in data

Related