JSON Files

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Instruction

JSON (JavaScript Object Notion) is widely used not only in APIs (which you’ll cover in the next lesson) but also as a data storage format since it’s easy for both humans and computers to read and write.

Reading JSON Files

Just as there’s a csv module in the Python Standard Library for working with CSV data, there’s also a json module for doing the same with JSON data.

import json

with open("some-file.json", "r") as file:
  data = json.load(file)

print(data)
[
  {
    "name": "Python",
    "creator": "Guido van Rossum",
    "year_appeared": 1991
  },
  {
    "name": "Swift",
    "creator": "Chris Lattner",
    "year_appeared": 2014
  },
  {
    "name": "Kotlin",
    "creator": "Jetbrains",
    "year_appeared": 2011
  }
]
[{'name': 'Python', 'creator': 'Guido van Rossum', 'year_appeared': 1991},
 {'name': 'Swift', 'creator': 'Chris Lattner', 'year_appeared': 2014},
 {'name': 'Kotlin', 'creator': 'Jetbrains', 'year_appeared': 2011}]

Handling Decoding Errors

There’s always a chance that the JSON file might not be formatted appropriately. In practice, you’ll want to wrap your file-reading code inside a try block to catch a JSON decoding error, along with other errors that are likely to happen while reading files, as shown below:

import json

try:
  with open('some-file.json', 'r') as file:
    data = json.load(file)
    print(data)
except json.JSONDecodeError as e:
  print(f"JSON decoding error: {e}")
except FileNotFoundError:
  print("File not found.")

Writing JSON Files

To write data to a JSON file, you need to:

import json

data = {
  "name": "C",
  "creator": "Dennis Ritchie",
  "year_appeared": 1972
}

with open("another-file.json", "w") as file:
  json.dump(data, file)
{"name": "C", "creator": "Dennis Ritchie", "year_appeared": 1972}
  json.dump(data, file, indent=4)
data = {
  "name": "C",
  "creator": "Dennis Ritchie",
  "year_appeared": 1972
}

Working With JSON Strings

In addition to providing ways to read and write to JSON files, the json module also provides methods for reading and writing data from and to JSON strings.

import json

json_string = '''
{
  "name": "Ruby",
  "creator": "Yukihiro Matsumoto",
  "year_appeared": 1995
}
'''
data = json.loads(json_string)
print(data)
import json

data = {
  "name": "Perl",
  "creator": "Larry Wall",
  "year_appeared": 1987
}
json_string = json.dumps(data, indent=4)
print(json_string)
{
  "name": "Perl",
  "creator": "Larry Wall",
  "year_appeared": 1987
}
See forum comments
Download course materials from Github
Previous: CSV Files Demo Next: JSON Files Demo