Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't encode content of keys from json

Tags:

python

json

I would like to print every value that belongs to my id key in my json file. I'm using the below code to print the whole file:

import json

from pprint import pprint

with open('f:\Docs\testList.json') as data_file:    

    data = json.load(data_file)

pprint( data )

And here is the json

{ "clubs": [
    {
        "location": "Dallas",
        "id": "013325K52",
        "type": "bar"
    },

    {
        "location": "Dallas",
        "id": "763825X56",
        "type": "restaurant"
    }
] }

It works correctly, however I can't figure out the type of the data_file and data variables, therefore I have no idea how could I write a for loop to print the content. I'm really new to Python, but in pseudo code I would do something like this (if I assume data is an array (or Python list) of dictionary objects):

for dictionaryVar in jsonArray

    print dictionaryVar["id"]

or

 for dictionaryVar in jsonArray

        if dictionaryVar containsKey: "id"

            print dictionaryVar["id"]

I would really appreciate if somebody could show me the right way or give guidance, because I don't really have an idea. I checked the docs of the json module, but couldn't figure out what it really does and how.

like image 432
sabiv Avatar asked Dec 27 '25 23:12

sabiv


2 Answers

data_file is a TextIOWrapper, that is: a file object used for reading text. You should not care about it.

data is a dict. Dictionaries map key-value pairs, but you probably already know that. data has one key, "clubs", which maps to a list. This list contains other dictionaries.

Your pseudo-code:

for dictionaryVar in jsonArray
    print dictionaryVar["id"]

corresponds to the following Python code:

for item in data['clubs']:
    print item['id']

Your pseudo-code:

for dictionaryVar in jsonArray
    if dictionaryVar containsKey: "id"
        print dictionaryVar["id"]

corresponds to the following Python code:

for item in data['clubs']:
    if 'id' in item:
        print item['id']
like image 130
Andrea Corbellini Avatar answered Dec 30 '25 23:12

Andrea Corbellini


This should be fairly simple, here is a quite explicit way of doing it (i made it longer so it's clearer for you, you could do this more efficiently)

import json

from pprint import pprint

with open('f:\Docs\testList.json') as data_file:    
    data = json.load(data_file)
    clubs = data['clubs']
    for club in clubs:
        # Use dict.get() here to default value to None if
        # it doesn't exist
        club_id = club.get('id', None)
        if club_id is not None:
            print club_id
like image 39
nichochar Avatar answered Dec 30 '25 23:12

nichochar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!