在 Python 中,json 模块提供了处理 JSON 格式数据的功能。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,通常用于在不同语言之间传递数据。以下是一些常用的 JSON 操作:

将 Python 对象转换为 JSON 字符串

使用 json.dumps() 函数可以将 Python 对象(字典、列表等)转换为 JSON 格式的字符串:
import json

# 创建一个字典
person = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# 将字典转换为 JSON 字符串
json_string = json.dumps(person)
print(json_string)

将 JSON 字符串转换为 Python 对象

使用 json.loads() 函数可以将 JSON 格式的字符串转换为 Python 对象:
# 将 JSON 字符串转换为字典
new_person = json.loads(json_string)
print(new_person)

读取 JSON 文件

使用 json.load() 函数可以从 JSON 文件中读取数据:
# 从 JSON 文件中读取数据
with open("data.json", "r") as file:
    data = json.load(file)
    print(data)

将 Python 对象写入 JSON 文件

使用 json.dump() 函数可以将 Python 对象写入 JSON 文件:
# 将字典写入 JSON 文件
with open("output.json", "w") as file:
    json.dump(person, file)

处理 JSON 中的嵌套结构

如果 JSON 中包含嵌套结构,可以通过 json.dumps() 的 indent 参数来提高可读性:
# 创建包含嵌套结构的字典
nested_data = {
    "name": "John",
    "age": 30,
    "address": {
        "city": "New York",
        "zipcode": "10001"
    }
}

# 将包含嵌套结构的字典转换为 JSON 字符串(带缩进)
nested_json_string = json.dumps(nested_data, indent=2)
print(nested_json_string)

这只是 JSON 操作的基础,json 模块还提供了其他一些参数和函数,可以更灵活地处理不同的情况。在处理 JSON 数据时,确保了解数据的结构和预期的格式,以便正确地使用 JSON 模块。


转载请注明出处:http://www.zyzy.cn/article/detail/13346/Python 基础