在Python中,你可以使用内置的 json 模块来处理JSON数据。以下是一些基本的JSON操作的示例:

将Python对象转换为JSON字符串:
import json

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

# 将Python字典转换为JSON字符串
json_string = json.dumps(data, indent=2)

print(json_string)

将JSON字符串解析为Python对象:
import json

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

# 将JSON字符串解析为Python字典
data = json.loads(json_string)

print(data)

从文件中读取JSON数据:
import json

# 从文件中读取JSON数据
with open('data.json', 'r') as file:
    data = json.load(file)

print(data)

将Python对象写入JSON文件:
import json

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

# 将Python字典写入JSON文件
with open('output.json', 'w') as file:
    json.dump(data, file, indent=2)

这些是基本的JSON处理方法。json.dumps 用于将Python对象转换为JSON字符串,而 json.loads 用于将JSON字符串解析为Python对象。json.dump 和 json.load 用于文件读写。

请注意,在处理JSON时,确保输入数据符合JSON格式,否则可能会引发 json.JSONDecodeError 或 json.JSONEncodeError。


转载请注明出处:http://www.pingtaimeng.com/article/detail/13290/Python3