}json.dump( code example
Example 1: python json dump to file
import json
with open('data.json', 'w') as f:
json.dump(data, f)
Example 2: json load from file python 3
import json
with open('file_to_load.json', 'r') as file:
data = json.load(file)
Example 3: python json dump format
>>> import json
>>>
>>> your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print(json.dumps(parsed, indent=4, sort_keys=True))
[
"foo",
{
"bar": [
"baz",
null,
1.0,
2
]
}
]
Example 4: load json
import json
with open('data.txt') as json_file:
data = json.load(json_file)
Example 5: json dumps python
# How to encode JSON as a string
import json
print(json.dumps({'a': 1, 'b': 2}) # '{ "a": 1, "b": 2 }'
print(json.dumps({'b': 1, 'a': 2}, sort_keys=True, indent=4))
# {
# "a": 2,
# "b": 1
# }
Example 6: python json.dumps pretty print
json.dumps(x, indent=4)