create a json file in python

To create a JSON file in Python, we can use the built-in json module. Here's a simple example:

main.py
import json

# create a dictionary object
data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# open a file for writing
with open("data.json", "w") as outfile:
    # write the dictionary object to the file
    json.dump(data, outfile)
253 chars
14 lines

In this example, we first define a dictionary object called data. We then use the open() function to open a file called "data.json" in write mode ("w"), and a with block to ensure proper closing of the file. We then use the json.dump() function to write the contents of the data dictionary to the file in JSON format.

If we want to pretty-print the JSON output with indentation, we can add the indent parameter to the json.dump() function:

main.py
json.dump(data, outfile, indent=4)
35 chars
2 lines

This will add 4 spaces of indentation for each level of the JSON hierarchy.

And that's it! With just a few lines of code, we can create a JSON file from a Python dictionary.

gistlibby LogSnag