How do I write JSON data to a file?

 

You can write JSON data to a file in Python using the json module. Here's how you can do it:

Example:

python
import json # Sample JSON data data = { "name": "John Doe", "age": 30, "city": "New York" } # Specify the file path where you want to save the JSON data file_path = "data.json" # Write JSON data to the file with open(file_path, "w") as json_file: json.dump(data, json_file) print("JSON data has been written to", file_path)

In this example:

  1. We import the json module, which provides functions for working with JSON data.

  2. We define a sample JSON data structure in the data dictionary.

  3. We specify the file_path variable with the path where you want to save the JSON data. You can replace "data.json" with the desired file path.

  4. We use the with statement to open the file specified by file_path in write mode ("w"). This ensures that the file is properly closed after writing.

  5. Inside the with block, we use the json.dump() function to write the JSON data from the data dictionary to the file.

  6. Finally, we print a message to confirm that the JSON data has been written to the file.

After running this code, the JSON data will be saved in the specified file in JSON format.

Make sure to replace the sample data dictionary with your own JSON data, and specify the desired file_path for your use case.

Comments