怎么用python处理json数据

32次阅读
没有评论

共计 807 个字符,预计需要花费 3 分钟才能阅读完成。

在 Python 中,处理 JSON 数据十分简单。可以使用 json 模块来加载和转换 JSON 数据:

1. 将 JSON 字符串转换为 Python 对象

import json

json_str = '{"name": "Alice", "age": 25}'
data = json.loads(json_str)
print(data["name"])  # 输出:Alice

在上述示例中,首先使用 json.loads() 函数将 JSON 字符串转换为 Python 对象。然后,可以像访问普通字典一样通过键来访问 JSON 数据的值。

2. 将 Python 对象转换为 JSON 字符串

import json

data = {"name": "Alice", "age": 25}
json_str = json.dumps(data)
print(json_str)  # 输出:{"name": "Alice", "age": 25}

在上述示例中,使用 json.dumps() 函数将 Python 对象转换为 JSON 字符串。

3. 读取 JSON 文件并将其转换为 Python 对象

import json

with open("data.json") as file:
    data = json.load(file)
print(data["name"])  # 输出:Alice

在上述示例中,使用 json.load() 函数从文件中读取 JSON 数据并将其转换为 Python 对象。

4. 将 Python 对象写入 JSON 文件

import json

data = {"name": "Alice", "age": 25}
with open("data.json", "w") as file:
    json.dump(data, file)

在上述示例中,使用 json.dump() 函数将 Python 对象写入 JSON 文件。

以上是一些常见的 JSON 数据处理操作。根据具体需求,还可以使用更多的 json 模块函数和方法来处理和操作 JSON 数据。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-13发表,共计807字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)