Working With JSON Data in Python

Reading JSON

[1]:
import json

json.load

Reads from a file path / object

[2]:
with open('testfiles/animals.json', 'r') as f:
    json_list = json.load(f)

print(json_list)
[{'animal': {'name': 'Henning', 'species': 'House Cat', 'relatives': [{'name': 'Fluffy', 'species': 'Norwegian Forrest'}]}}, {'animal': {'name': 'Fido', 'species': 'Dog', 'relatives': [{'name': 'Jeff', 'species': 'Puddle'}, {'name': 'Minna', 'species': 'Labrador'}]}}]
[12]:
[i['animal']['relatives'] for i in json_list]
[12]:
[[{'name': 'Fluffy', 'species': 'Norwegian Forrest'}],
 [{'name': 'Jeff', 'species': 'Puddle'},
  {'name': 'Minna', 'species': 'Labrador'}]]

json.loads

Reads the content of the file

[7]:
with open('testfiles/animals.json', 'r') as f:
    txt = f.read()
    js = json.loads(txt)

print(js)
[{'animal': {'name': 'Henning', 'species': 'House Cat', 'relatives': [{'name': 'Fluffy', 'species': 'Norwegian Forrest'}]}}, {'animal': {'name': 'Fido', 'species': 'Dog', 'relatives': [{'name': 'Jeff', 'species': 'Puddle'}, {'name': 'Minna', 'species': 'Labrador'}]}}]
[8]:
[i['animal']['relatives'] for i in js]
[8]:
[[{'name': 'Fluffy', 'species': 'Norwegian Forrest'}],
 [{'name': 'Jeff', 'species': 'Puddle'},
  {'name': 'Minna', 'species': 'Labrador'}]]

Writing JSON

json.dumps

Serialize obj to a JSON formatted str

[14]:
dict = {'name' : 'Claus', 'age' : 120, 'cpr' : 1234}
with open('testfiles/students.json', 'w') as f:
    js =json.dumps(dict)
    f.write(js)
[15]:
with open('testfiles/students.json', 'r') as f:
    js = json.load(f)
print(js)
{'name': 'Claus', 'age': 120, 'cpr': 1234}

json.dump

Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object)

[16]:
from io import StringIO
io = StringIO()
teachers = [{'name' : 'Claus', 'age' : 120}, {}]
with open('testfiles/teachers.json', 'w') as f:
    json.dump(teachers, io)
    f.write(io.getvalue())
[17]:
with open('testfiles/teachers.json', 'r') as f:
    js = json.load(f)
print(js)
[{'name': 'Claus', 'age': 120}, {}]

10 minutes exercise

  1. From this api https://api.github.com/orgs/python-elective-fall-2019/repos get all names of the repos and write them to a text file.

  2. Get all filenames of files ending with .ipynb in the code_examples folder in the Lesson-09-context-managers repository.

[11]: