Getting specific field values from Json Python

13,862

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
Share:
13,862
Matheus Maciel
Author by

Matheus Maciel

Updated on June 04, 2022

Comments

  • Matheus Maciel
    Matheus Maciel almost 2 years

    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"
     }]
    
  • Matheus Maciel
    Matheus Maciel over 5 years
    Thank you so much! You helped me a lot! =]