Python: JSON

By Xah Lee. Date: . Last updated: .

The JSON module

The json module lets you convert JSON Data Format to from Python object.

Basically, JavaScript array is Python's list, and JavaScript object is Python's dictionary.

Export to JSON

json.dumps(obj)

Convert Python obj to JSON string.

json.dump(python_obj, file_obj)

Convert Python object to JSON, write to file file_obj.

Example. Python to JSON string

# python object to JSON string

import json

# python tuple
print(json.dumps((1,2,3)))
# [1, 2, 3]

# python list
print(json.dumps([1, 2, "abc"]))
# [1, 2, "abc"]

# python dict
print(json.dumps({"john":3, "mary":4, "joe":5}))
# {"john": 3, "mary": 4, "joe": 5}

# python special values
print(json.dumps([True, False, None]))
# [true, false, null]

Example. Python to JSON file

# Example. Python to JSON file

import json

xdata = {
    "name": "joe",
    "id": 2967637,
    "colors": ["red", "blue"],
    "address": {"city": "NY", "country": "USA"},
}

outfile_path = "xx-sample.json"

# Writing to file
with open(outfile_path, "w", encoding="utf-8") as xfile:
    json.dump(xdata, xfile)

Import from JSON

json.loads(jsonStr)

Convert JSON string into Python.

json.load(jsonStr, file_obj)

Convert JSON file file_obj to Python.

Example. JSON string to Python

# convert JSON string to Python data structure

import json

json_str = '[true, false, null, 2, 1.0, 4.3, {"jane": 49, "joe":72}]'

python_obj = json.loads(json_str)

print(python_obj)
# [True, False, None, 2, 1.0, 4.3, {'jane': 49, 'joe': 72}]

Example. JSON file to Python object

# example of reading JSON from a file

import json

xdata = {"name": "joe", "year": 2026}

json_file_path = "xx.json"

# create a json file
with open(json_file_path, "w", encoding="utf-8") as xfile:
    json.dump(xdata, xfile, indent=4, ensure_ascii=False)

# read a json file
xresult = json.loads(open(json_file_path).read())

print(xresult)
# {'name': 'joe', 'year': 2026}

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

JSON