Python Json Module: Reference and Examples

Last updated:
Table of Contents

Python 3 used in examples

json.loads example

Reads a valid json string into a variable

import json

json.loads("""{"foo":123, "bar": "baz"}""")
# >>> {'foo': 123, 'bar': 'baz'}

json.dumps example

Prints dictionaries, lists and primitive types such as arrays

import json

json.dumps({"foo":123, "bar":"baz"})
# >>> '{"foo": 123, "bar": "baz"}'

json.load vs json.loads

json.load json.loads
Read a json file into a python variableRead a json string into a python variable
json.load(open("myfile.json"))json.loads("""{"foo":123, "bar": "baz"}""")

Python types vs json types

left: json types/values, right: python types/values

JSON Python
object dict
array list
string str
number int
number float
true True
false False
null None

Json string to dict

Use json.loads('{"foo":"bar"}') to load a json string representing an object into a python dict.

import json

# >>> {'foo': 'bar'}

Json string to list

You can use json.loads('["foo","bar"]') to load a json string representing an array into a python list:

import json

# >>> ['foo', 'bar']

Load json file to dict

Will result in a list if your json file has arrays as top-level entities

Use json.load("/path/to/file.json")

import json

# >>> {'foo': 'bar'}

Dialogue & Discussion