📜  json 加载 python (1)

📅  最后修改于: 2023-12-03 14:43:34.427000             🧑  作者: Mango

JSON 加载 Python

介绍

在 Python 中,JSON (JavaScript Object Notation) 是一种轻量级数据交换格式,通常用于跨网络传输和存储数据。Python 中的标准库中已经包含了 JSON 模块,可以轻松加载和解析 JSON 数据。

JSON 数据可以由 Python 对象 (例如 dict、list、int、str、bool、float 和 NoneType) 直接表示,通过 JSON 序列化和反序列化,可以在 Python 和其他编程语言之间进行数据交互。

在 Python 中,可以使用 JSON 格式来读取和写入配置文件、数据持久化,以及进行 API 数据传输等操作。

加载 JSON 数据

在 Python 中,可以使用 json 模块的 loads() 函数将 JSON 字符串转换为 Python 对象。

import json

# JSON 字符串
json_str = '{"name": "Alice", "age": 30, "is_married": true}'

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

# 打印 Python 对象的值
print(data) # 输出: {'name': 'Alice', 'age': 30, 'is_married': True}
加载 JSON 文件

在 Python 中,可以使用 json 模块的 load() 函数将 JSON 文件读取为 Python 对象。

import json

# 从 JSON 文件中加载数据
with open('data.json', 'r') as f:
    data = json.load(f)

# 打印 Python 对象的值
print(data) # 输出: {'name': 'Alice', 'age': 30, 'is_married': True}
解析复杂的 JSON 数据

在 Python 中,可以使用 json 模块的 loads() 函数解析复杂的 JSON 数据,包括嵌套的字典、列表、布尔型、数字等。

import json

# JSON 字符串
json_str = '''
{
    "name": "Alice",
    "age": 30,
    "is_married": true,
    "hobbies": ["reading", "painting", "travelling"],
    "address": {
        "street": "123 Main St",
        "city": "New York",
        "state": "NY",
        "postal_code": "10001"
    }
}
'''

data = json.loads(json_str)
print(data['name']) # 输出: Alice
print(data['hobbies'][0]) # 输出: reading
print(data['address']['city']) # 输出: New York
总结

Python 中的 json 模块可以帮助我们轻松地加载和解析 JSON 数据。我们可以使用 loads() 函数将 JSON 字符串转换为 Python 对象,或使用 load() 函数从 JSON 文件中读取数据。在解析复杂的 JSON 数据时,我们可以按照字典或列表的方式访问和操作 JSON 对象的值。