Chapter 6: JSON files

Writing to a JSON file

face Josiah Wang

Conversely, you can also easily write a Python object to a JSON string. The fancy term is serialisation (converting a data object into a string representation, usually for storage or transmission).

To write your data into a JSON file, use json.dump(). The following code serialises data to JSON format and saves it in a file called output.json.

import json

data = {"course": "Introduction to Machine Learning", "term": 1}

with open("output.json", "w") as jsonfile: 
    json.dump(data, jsonfile)

To write your data to a string (and do something else with it later), use json.dumps().

json_string = json.dumps(data)
print(json_string)  # {"course": "Introduction to Machine Learning", "term": 1}