
Python json.dumps - How to write json data to a file in Python
To write data (as a Python list or dictionary) to a json file, the json.dumps()
is needed to convert it to the string.
import json
a = [1, 2, 3]
j = json.dumps(a)
with open('a.json', 'w') as f:
f.write(j)
The a.json
contains:
[1, 2, 3]
Example
import json
a = {'r': [1, 2, 3], 'd': {'x': 5, 'y': 7}}
j = json.dumps(a)
with open('a.json', 'w') as f:
f.write(j)
a.json
{"r": [1, 2, 3], "d": {"x": 5, "y": 7}}
Indent
import json
a = {'r': [1, 2, 3], 'd': {'x': 5, 'y': 7}}
j = json.dumps(a, indent=4)
with open('a.json', 'w') as f:
f.write(j)
If the indent option of json.dumps()
is 4, the data is printed in the json file with 4 indents.
a.json
{
"r": [
1,
2,
3
],
"d": {
"x": 5,
"y": 7
}
}
Sort keys
import json
a = {'r': [1, 2, 3], 'd': {'x': 5, 'y': 7}}
j = json.dumps(a, indent=4, sort_keys=True)
with open('a.json', 'w') as f:
f.write(j)
If the sort_keys option of json.dumps()
is true, the printed data is sorted by dictionary keys.
a.json
{
"d": {
"x": 5,
"y": 7
},
"r": [
1,
2,
3
]
}
The dictionary a
starts with r
key but the printed data starts with d
key.
Comments
Powered by Markdown