write json to a file in python

In Python, you can write JSON data to a file using the json module. Here's an example:

main.py
import json

# Sample data to be written
data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# Open file for writing
with open('data.json', 'w') as outfile:
    # Write JSON data to file
    json.dump(data, outfile)
234 chars
14 lines

In this example, we import the json module, create a dictionary of sample data, and open a file called data.json for writing using the open() function. We then use the json.dump() method to write the JSON data to the file object.

Note that we used the with statement to open the file. This ensures that the file is automatically closed once the block of code inside the with statement is executed. It's good practice to use with when dealing with file I/O in Python.

To read data from a JSON file, you can use the json.load() function instead:

main.py
import json

# Open file for reading
with open('data.json', 'r') as infile:
    # Load JSON data from file
    data = json.load(infile)

# Access data from dictionary
print(data['name'])  # Output: John
203 chars
10 lines

In this example, we open the data.json file for reading and use the json.load() function to read the JSON data from the file into a dictionary. We can then access the data from the dictionary as usual (in this case, we print the value associated with the name key).

related categories

gistlibby LogSnag