To create a JSON file in Python, we can use the built-in json
module. Here's a simple example:
main.py253 chars14 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.py35 chars2 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