Python: Read Write JSON

By Xah Lee. Date: . Last updated: .

JSON Library

The JSON library converts JSON Data Format to from Python nested dictionary/list. Basically, JavaScript array is Python's list, and JavaScript object is Python's dictionary.

json.dumps(obj)
Convert Python obj to JSON string.
json.loads(jsonStr)
Convert JSON string into Python nested dictionary/list.

For reading/writing to file, use:

json.dump(python_obj, file_thing)
Convert Python nested dictionary/list to JSON (output to file-like object)
json.load(jsonStr, file_thing)
Convert JSON string into Python nested dictionary/list and write into a file.

Example, Python Object to JSON

Here's example of converting Python object to JSON:

# python nested dictionary/list to JSON

import json

bb = ['x3', {'x4': ('8', None, 1.0, 2)}]

print(json.dumps(bb))
# ["x3", {"x4": ["8", null, 1.0, 2]}]

Example, JSON to Python Object

Here's example of converting JSON to Python object:

# convert JSON to Python nested dictionary/list

import json

json_data = '["x3", {"x4": ["8", null, 1.0, 2]}]'

python_obj = json.loads(json_data)

print(python_obj)
# ['x3', {'x4': ['8', None, 1.0, 2]}]

Here's example of reading JSON from a file:

# example of reading JSON from a file

import json
my_data = json.loads(open("xyz.json").read())

print(my_data)

Example, Pretty Print JSON

You can use the json lib to pretty print nested hash, by giving the argument indent=1.

import json

hh = {3:4,5:6, 7:{9:{8:10},11:12}}

print(json.dumps(hh,indent=1))

# {
#  "3": 4,
#  "5": 6,
#  "7": {
#   "9": {
#    "8": 10
#   },
#   "11": 12
#  }
# }

Python, Data Structure