How to Write JSON in Python
Python’s json
module provides the dumps()
function to convert Python objects to JSON strings. Unlike Ruby where you call .to_json()
on objects, Python uses a function that accepts the object as a parameter.
import json
data = {"name": "Claus Witt", "ideas": ["idea one", "idea two"]}
json_string = json.dumps(data)
print(json_string)
You can also write JSON directly to a file:
import json
data = {"name": "Claus Witt", "blog": "clauswitt.com"}
with open("output.json", "w") as f:
json.dump(data, f, indent=2)