import json
# 示例 JSON 字符串
json_string = '{"name": "Alice", "age": 25, "city": "New York"}'
# 使用 json.loads() 将 JSON 字符串解析为 Python 字典
data = json.loads(json_string)
# 输出解析后的数据
print(data)
# 结果: {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 如果要从文件中读取 JSON 数据,可以使用 json.load()
# 假设有一个名为 data.json 的文件,内容如下:
# {
# "name": "Bob",
# "age": 30,
# "city": "San Francisco"
# }
# 打开并读取 JSON 文件
with open('data.json', 'r') as file:
data_from_file = json.load(file)
# 输出从文件中读取的数据
print(data_from_file)
# 结果: {'name': 'Bob', 'age': 30, 'city': 'San Francisco'}
json.loads()
:用于将 JSON 格式的字符串解析为 Python 对象(通常是字典)。json.load()
:用于从文件中读取 JSON 数据并解析为 Python 对象。json.loads()
处理 JSON 字符串,然后展示了如何使用 json.load()
从文件中读取 JSON 数据。上一篇:python 两个list合并
下一篇:python中float的含义
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站