JSON

Saving and Reading Data with json: Useful Examples

JSON (JavaScript Object Notation) is a lightweight data-interchange format that’s easy for humans to read and write. It’s widely used to store and exchange data, and Python has built-in support for reading and writing JSON data.

Here’s how you can work with JSON data in Python.

Saving Data to JSON

To write data to a JSON file, you can use the json module and the dump or dumps methods.

Using json.dump

The json.dump method writes a Python object to a file-like object.

import json

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

with open('data.json', 'w') as file:
    json.dump(data, file)

This code will create a file called data.json and write the data to it.

Using json.dumps

The json.dumps method returns a JSON string representation of the Python object. You can write this string to a file.

json_str = json.dumps(data)

with open('data.json', 'w') as file:
    file.write(json_str)

Reading Data from JSON

You can read JSON data from a file using the json.load or json.loads methods.

Using json.load

The json.load method reads a file-like object containing a JSON document and returns a Python object.

with open('data.json', 'r') as file:
    data = json.load(file)

print(data)  # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}

Using json.loads

If you have a JSON string, you can convert it to a Python object using the json.loads method.

with open('data.json', 'r') as file:
    json_str = file.read()

data = json.loads(json_str)

print(data)  # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}

Summary

The json module in Python makes it easy to read and write JSON data. You can convert Python objects to JSON and back with just a few lines of code. Whether you’re working with local files or receiving JSON data from a web service, these tools can simplify your development process.

Feel free to experiment with these examples to get a better understanding of how JSON data handling works in Python!