Technology Encyclopedia Home >How to use JSON in Python?

How to use JSON in Python?

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. In Python, you can use the built-in json module to work with JSON data.

Here's a brief explanation and example of how to use JSON in Python:

1. Import the json module

First, you need to import the json module, which provides methods to work with JSON data.

import json

2. Convert JSON string to Python object (dictionary or list)

Use the json.loads() method to convert a JSON string to a Python object (usually a dictionary or a list).

json_string = '{"name": "John", "age": 30, "city": "New York"}'
python_obj = json.loads(json_string)

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

3. Convert Python object to JSON string

Use the json.dumps() method to convert a Python object (dictionary or list) to a JSON string.

python_obj = {"name": "John", "age": 30, "city": "New York"}
json_string = json.dumps(python_obj)

print(json_string)  # Output: {"name": "John", "age": 30, "city": "New York"}

4. Read JSON data from a file

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

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

print(data)

5. Write JSON data to a file

To write JSON data to a file, you can use the json.dump() method.

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

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

If you're working with large datasets or need to manage JSON data in a cloud environment, consider using Tencent Cloud's Object Storage service, which allows you to store and retrieve JSON files easily. Additionally, Tencent Cloud's API Gateway can help you manage and secure your APIs that handle JSON data.