json数据保存和读取

保存示例:

import json

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

with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f)
    print("保存成功")

这个示例将 Python 字典 data 序列化为 JSON 格式,并将其写入到一个名为 data.json 的文件中。with 语句确保在写入完毕后正确地关闭文件对象。


要读取上述代码生成的 data.json 文件,可以使用 json.load() 函数将 JSON 数据加载回到 Python 对象中。示例代码如下:
import json

with open('data.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

print(data)

运行上述代码后,会将 data.json 文件中的 JSON 数据加载回到 Python 对象 data 中,并使用 print() 函数将其打印出来。输出结果为:

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

注意,在使用 json.load() 函数加载 JSON 数据时,需要将打开文件的模式设置为只读模式('r'),因为我们只是想从文件中读取数据。如果使用可写模式('w')打开文件,则会清空文件中的内容并覆盖它,这可能会导致数据丢失

posted @ 2023-05-15 11:01  __username  阅读(148)  评论(0编辑  收藏  举报

本文作者:DIVMonster

本文链接:https://www.cnblogs.com/guangzan/p/12886111.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。