json库
json库通常用于解析json文件以及生成json文件,通常读入json文件需要伴随着文件的打开模式
前置学习-文件打开模式
r 代表只读模式
w 可写
r+ 可读可写,文件必须存在,才能读写
w+ 可读可写,文件不存在时,会创建文件
rb+ 二进制可读可写
wb+ 二进制可读可写
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 fpjson.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_ENDfp.write('nihaoa, zhongguo')fp.close()
json.dumps()序列化为json字符串
with open('note.json', 'r+') as fp:print(fp.read())print(type(content)) # 输出为dictdata = json.dumps(content)print(type(data)) # 输出为字符串fp.close()