Convert a Python list to JSON
A list and a list of dicts both go through json.dumps(). The result is one JSON array, not a dict and not one document per row.
json.dumps() accepts a list
Python list to JSON is the same function used for a dictionary. json.dumps() turns a list into a JSON array and returns a string.
import json
names = ["Ada", "Lin"]
print(json.dumps(names))
# ["Ada", "Lin"]
True, False, and None inside the list become true, false, and null. You do not replace those words yourself. A dict uses the same function; that case is in dict to JSON with json.dumps().
A list of dicts is one JSON array
import json
people = [
{"name": "Ada", "active": True},
{"name": "Lin", "active": False},
]
text = json.dumps(people, indent=2)
print(text)
The printed document is a single array of objects:
[
{"name": "Ada", "active": true},
{"name": "Lin", "active": false}
]
Do not join separate json.dumps() calls with commas by hand. That is easy to get wrong when a value contains a comma, and it is unnecessary: pass the whole list. If you want one JSON object per line instead of one array, write JSON Lines.
Write a list to a JSON file
Use json.dump() when the destination is a file. This is the list version of writing a dict to a JSON file.
import json
people = [{"name": "Ada", "active": True}]
with open("people.json", "w", encoding="utf-8") as file:
json.dump(people, file, indent=2, ensure_ascii=False)
file.write("\n")
"w" replaces an existing file. ensure_ascii=False keeps non-ASCII characters readable; the encoding="utf-8" argument is what makes the file UTF-8.
A tuple becomes an array; a set does not encode
import json
print(json.dumps((1, 2)))
# [1, 2]
try:
json.dumps({"python", "json"})
except TypeError as exc:
print(exc)
JSON has arrays, not tuples or sets. A tuple is encoded as an array, and reading it back with json.loads() returns a list. A set raises TypeError: Object of type set is not JSON serializable. Convert it yourself when order matters:
tags = sorted({"python", "json"})
print(json.dumps(tags))
# ["json", "python"]
sorted() needs members that can be compared with each other. Mixed strings and numbers need a different ordering rule. Datetimes and other unsupported values are covered in serialization errors.