sabiv sabiv - 4 months ago 11
JSON Question

Can't encode content of keys from 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.

Answer

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']
Comments