json
Converts Python data to JSON text and back. The basis for saving data and communicating with APIs.
- Returns
dumps()returns a string, andloads()returns a Python object, most often adictorlist.
Example
#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__)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
#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 withdumps()ordump().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 toFalseso 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=strwill write dates as text, for example.
More examples
#import json
city = {"city": "Zürich", "students": 120}
print(json.dumps(city))
print(json.dumps(city, ensure_ascii=False, indent=2))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)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=stror by converting them to dictionaries first.
Related entries
#- dict()Creates a dictionary from key-value pairs or keyword arguments.
- open()Opens a file for reading or writing and returns a file object.
- withA context manager: automatic setup and cleanup of resources.
- datetimeDates and times: creating, formatting, parsing from text, and calculations on time intervals.
- pathlibPaths as objects: joining with the / operator, reading the parts of a path, and working with files.
- csvReading and writing CSV files, that is tables saved as text in which values are separated by a comma or a semicolon.
Practise it in lessons
#Spotted a mistake or missing an example? Write to us.