Python Json Module

JSON stands for JavaScript Object Notation and is a lightweight format for storing and transporting data. JSON is often used when data is sent from a server to a web page.

Python has the built-in module json, which allow us to work with JSON data.

import json

JSON Data Types

A JSON object is similar to a Python dictionary, but has the following differences:

  • JSON Keys are always string.
  • Strings are always enclosed with double quotes.
  • A JSON boolean start with lowercase letters.
  • null is the JSON equivalent of Python None.

The data types JSON supports are:

  • String
  • Number
  • boolean
  • null
  • Object
  • Array

Example:

{
  "name": "Charles",
  "age": 33,
  "has_hair": false,
  "hobbies": ["photography", "running"],
  "appearance": {
    "eyes": "brown",
    "hair_color": null
  }
}

JSON loads() method

With the json.loads method, you can parse a JSON object and transform it to a Python dictionary:

>>> import json

>>> json_person = '{"name": "Charles", "age": 33, "has_hair": false, "hobbies": ["photography", "running"]}'
>>> python_person = json.loads(json_person)
>>> python_person
# {'name': 'Charles', 'age': 33, 'has_hair': False, 'hobbies': ['photography', 'running']}

>>> type(python_person)
# <class 'dict'>

>>> python_person.get("name")
# 'Charles'

JSON dumps() method

The other way around. The dumps() method transforms a Python object to a JSON string:

>>> import json

>>> python_person = {'name': 'Charles', 'age': 33, 'has_hair': False, 'hobbies': ['photography', 'running']}
>>> json_person = json.dumps(python_person)

>>> json_person
# '{"name": "Charles", "age": 33, "has_hair": false, "hobbies": ["photography", "running"]}'

>>> type(json_person)
# <class 'str'>

Reading and writing Json Files

Reading a Json File

>>> import json
>>> with open("filename.json", "r") as f:
...     json_content = json.loads(f.read())
...
>>> json.loads(json_content)
# {'name': 'Charles', 'age': 33, 'has_hair': False}

Writing a Json File

>>> import json

>>> person = {'name': 'Charles', 'age': 33}

>>> with open("filename.json", "w") as f:
...     f.write(json.dumps(person))

Python abs() built-in function Python aiter() built-in function Python all() built-in function Python any() built-in function Python ascii() built-in function Python bin() built-in function Python bool() built-in function Python breakpoint() built-in function Python bytearray() built-in function Python bytes() built-in function Python callable() built-in function Python chr() built-in function Python classmethod() built-in function Python compile() built-in function Python complex() built-in function Python delattr() built-in function Python dict() built-in function Python dir() built-in function Python divmod() built-in function Python enumerate() built-in function Python eval() built-in function Python exec() built-in function Python filter() built-in function Python float() built-in function Python format() built-in function Python frozenset() built-in function Python getattr() built-in function Python globals() built-in function Python hasattr() built-in function Python hash() built-in function Python help() built-in function Python hex() built-in function Python id() built-in function Python __import__() built-in function Python input() built-in function Python int() built-in function Python isinstance() built-in function Python issubclass() built-in function Python iter() built-in function Python len() built-in function Python list() built-in function Python locals() built-in function Python map() built-in function Python max() built-in function Python memoryview() built-in function Python min() built-in function Python next() built-in function Python object() built-in function Python oct() built-in function Python open() built-in function Python ord() built-in function Python pow() built-in function Python print() built-in function Python property() built-in function Python range() built-in function Python repr() built-in function Python reversed() built-in function Python round() built-in function Python set() built-in function Python setattr() built-in function Python slice() built-in function Python sorted() built-in function Python staticmethod() built-in function Python str() built-in function Python sum() built-in function Python super() built-in function Python tuple() built-in function Python type() built-in function Python vars() built-in function Python zip() built-in function