create a root element json in python

In Python, you can create a root element in JSON by first creating a Python dictionary using curly braces {} and then using the json.dump() function to save it to a JSON file.

Here's an example:

main.py
import json

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

with open("data.json", "w") as outfile:
    json.dump(data, outfile)
156 chars
11 lines

This will create a root element JSON file named "data.json" with the following content:

{
    "name": "John Doe",
    "age": 30,
    "city": "New York"
}
66 chars
6 lines

Note that the json.dump() function takes two arguments: the Python dictionary to be saved as JSON, and the file object to write the JSON to.

related categories

gistlibby LogSnag