json库使用教程

json库

json库通常用于解析json文件以及生成json文件,通常读入json文件需要伴随着文件的打开模式

前置学习-文件打开模式

r 代表只读模式
w 可写
r+ 可读可写,文件必须存在,才能读写
w+ 可读可写,文件不存在时,会创建文件
rb+ 二进制可读可写
wb+ 二进制可读可写
a 不能读取,追加模式,文件不存在时创建文件,追加写入
a+ 可以读取,追加模式,

加b的使用前,需要判断文件格式是否为纯文本数据

json.loads()加载json字符串

jsondata='''
{
    "name": "Alice",
    "age": 25,
    "address": {
        "street": "123 Main St",
        "city": "Wonderland",
        "zip": "12345"
    },
    "hobbies": ["reading", "gaming", "traveling"],
    "friends": [
        {"name": "Bob", "age": 23},
        {"name": "Charlie", "age": 24}
    ]
}
'''
json.loads(jsondata) # 从字符串读入

json.load()加载json文件

需要从文件读入json,内容时需要先打开文件

with open(file, 'r') as fp
    json.load(fp) # 从文件读入json信息

json.dump()落盘内容到文件

将对应内容写入到文件中

with open('note.json', 'w+') as fp:
    json.dump(content, fp, indent=2)
    fp.seek(0, 2) # 2 是OS.SEEK_END
    fp.write('nihaoa, zhongguo')
    fp.close()

json.dumps()序列化为json字符串

with open('note.json', 'r+') as fp:
    print(fp.read())
    print(type(content)) # 输出为dict
    data = json.dumps(content)
    print(type(data)) # 输出为字符串
    fp.close()
posted @ 2026-01-18 23:54  LemHou  阅读(2)  评论(0)    收藏  举报