How do I write JSON data to a file?

To write JSON data to a file in Python, you can use the json module.

Here's an example of how you can use the json module to write JSON data to a file:

import json

data = {
    "name": "John Smith",
    "age": 30,
    "city": "New York"
}

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

This will write the data contained in the data dictionary to a file called data.json in the current working directory. The dump() function takes two arguments: the data to be written, and the file object to which the data should be written.

Watch a course Python - The Practical Guide

The with statement is used to open the file and create a file object, and the json.dump() function is used to write the data to the file. The file is then automatically closed when the with block is exited.

You can also use the json.dumps() function to create a JSON string from the data, and then write that string to the file using the file object's write() method:

import json

data = {
    "name": "John Smith",
    "age": 30,
    "city": "New York"
}

json_data = json.dumps(data)

with open("data.json", "w") as outfile:
    outfile.write(json_data)