How does Python handle JSON files?

In Python, you can handle JSON files using the json module. Here are some examples of common JSON operations:

Read a JSON file.

import json

# 打开JSON文件
with open('data.json', 'r') as f:
    # 解析JSON数据
    data = json.load(f)

# 使用data变量访问JSON中的数据
print(data)

Write to a JSON file.

import json

# 要写入的数据
data = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

# 打开JSON文件
with open('data.json', 'w') as f:
    # 将数据写入JSON文件
    json.dump(data, f)

Convert a JSON string to a Python object.

import json

# JSON字符串
json_str = '{"name": "John", "age": 30, "city": "New York"}'

# 将JSON字符串转换为Python对象
data = json.loads(json_str)

# 使用data变量访问Python对象中的数据
print(data['name'])

Convert Python objects to JSON strings.

import json

# Python对象
data = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

# 将Python对象转换为JSON字符串
json_str = json.dumps(data)

# 输出JSON字符串
print(json_str)

In the examples above, json.load() is used to read JSON data from a file, while json.dump() is used to write data to a JSON file. json.loads() is used to convert a JSON string to a Python object, and json.dumps() is used to convert a Python object to a JSON string.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds