json

Converts Python data to JSON text and back. The basis for saving data and communicating with APIs.

Returns
dumps() returns a string, and loads() returns a Python object, most often a dict or list.
On this page

Example

#
Python
import json

student = {
    "name": "Emma",
    "points": 1240,
    "courses": ["HTML", "Python"],
    "premium": False,
    "mentor": None,
}

text = json.dumps(student)
print(text)

data = json.loads('{"level": 3, "badges": ["start", "streak_7"]}')
print(data["badges"][1], type(data).__name__)
Resultsaved result, you can check it
{"name": "Emma", "points": 1240, "courses": ["HTML", "Python"], "premium": false, "mentor": null}
streak_7 dict

Definition and usage

#

The json module converts dictionaries, lists, strings, numbers, booleans, and None into text in JSON format, and also reads such text back into Python objects. JSON is the most popular format for exchanging data between applications, APIs, and configuration files.

The functions ending in the letter “s” work on strings: dumps() creates text, and loads() reads it. The versions without the “s”, that is dump() and load(), write to a file and read from a file. In the conversion, True becomes true, None becomes null, and tuples turn into lists.

By default, non-ASCII characters, such as accented letters, are written as sequences like \u00fc. The ensure_ascii=False argument keeps them in readable form, and indent=2 spreads the result over many indented lines. Invalid text raises the json.JSONDecodeError exception.

Syntax

#
Syntax
import json

json.dumps(obj, indent=None, ensure_ascii=True, sort_keys=False)
json.loads(text)
json.dump(obj, file)
json.load(file)

Parameters

#
  • obj

    dict, list, str, int, float, bool, None

    The data to write with dumps() or dump().
  • indent

    int, optional

    The number of spaces of indentation. Without it, the whole JSON goes on one line.
  • ensure_ascii

    bool, default True

    Set it to False so that non-ASCII characters are written as they are, not as \u….
  • sort_keys

    bool, default False

    Sorts dictionary keys alphabetically.
  • default

    function, optional

    Called for objects that JSON does not support. default=str will write dates as text, for example.

More examples

#
Non-ASCII characters and indentation
Python
import json

city = {"city": "Zürich", "students": 120}

print(json.dumps(city))
print(json.dumps(city, ensure_ascii=False, indent=2))
Resultsaved result, you can check it
{"city": "Z\u00fcrich", "students": 120}
{
"city": "Zürich",
"students": 120
}
Writing and reading a JSON file
Python
import json

progress = {"student": "Emma", "done": ["1_1", "1_2"], "streak": 5}

with open("progress.json", "w", encoding="utf-8") as file:
    json.dump(progress, file, ensure_ascii=False, indent=2)

with open("progress.json", encoding="utf-8") as file:
    loaded = json.load(file)

print(loaded["done"])
print(loaded == progress)
Resultsaved result, you can check it
['1_1', '1_2']
True

Good practices

#
  • JSON requires double quotes around keys and strings. Text copied from print(dictionary), with single quotes, is not valid JSON.
  • Keys in JSON are always strings: the dictionary {1: "a"} will have the key "1" after writing and reading.
  • You can write dates and custom objects by passing default=str or by converting them to dictionaries first.

Related entries

#

Practise it in lessons

#

Spotted a mistake or missing an example? Write to us.