json.load vs. json.loads and json.dump vs. json.dumps
suggest changeThe json module can read and write JSON using either strings or file-like objects. Functions whose names end in s operate on strings: loads loads from a string, and dumps dumps to a string. The corresponding load and dump functions operate on file-like objects.
Here we use the string-based functions:
import json
data = {"foo": "bar", "baz": []}
json_string = json.dumps(data)
print(json_string)
# {"foo": "bar", "baz": []}
print(json.loads(json_string))
# {'foo': 'bar', 'baz': []}
And here we use the file-based functions:
import json
from io import StringIO
json_file = StringIO()
data = {"foo": "bar", "baz": []}
json.dump(data, json_file)
json_file.seek(0)
print(json_file.read())
# {"foo": "bar", "baz": []}
json_file.seek(0)
print(json.load(json_file))
# {'foo': 'bar', 'baz': []}
When using dump, pass the destination file object instead of capturing a return value. After writing to an in-memory file, move its cursor back to the beginning before reading it. A newly opened file is already positioned appropriately, so ordinary files can be handled as follows:
import json
json_file_path = "data.json"
data = {"foo": "bar", "baz": []}
with open(json_file_path, "w", encoding="utf-8") as json_file:
json.dump(data, json_file)
with open(json_file_path, encoding="utf-8") as json_file:
restored_data = json.load(json_file)
print(restored_data)
# {'foo': 'bar', 'baz': []}
The same functions work with newline-delimited JSON, where each line contains one JSON value:
import json
with open(file_path, encoding="utf-8") as json_file:
data = [json.loads(line) for line in json_file if line.strip()]
with open(file_path, "w", encoding="utf-8") as json_file:
for item in data:
json.dump(item, json_file)
json_file.write("\n")
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents