Python Json Module: Reference and Examples

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

json.loads('{"foo":"bar"}')
# >>> {'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

json.loads('["foo","bar"]')
# >>> ['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

json.loads('/path/to/file.json')
# >>> {'foo': 'bar'}

json.dumps, UTF-8 Characters

This is a common problem when we load json files with UTF-8/Unicode data:

Use json.dumps(data_dict, ensure_ascii=False):

import json

json_data_utf8 = json.load(open("my_utf8_file.json"))

print(json.dumps(json_data_utf8, ensure_ascii=False))

source-json-data my_utf8_file.json
    
json-dumps-utf8-bad-encoding BAD Default behaviour of json.dumps:
Broken encoding
    
json-dumps-ensure-ascii-false GOOD json.dumps() using ensure_ascii=False