Python实现写入json和jsonl文件操作方法详解

Python处理json文本文件主要是以下四个函数:

函数 作用
json.dumps 对数据进行编码,将python中的字典 转换为 字符串
json.loads 对数据进行解码,将 字符串 转换为 python中的字典
json.dump 将dict数据写入json文件中
json.load 打开json文件,并把字符串转换为python的dict数据

写入json的内容只能是dict类型,因此在构造写入json文件的内容时直接构造dict类型即可:

#写入json
tesdic = {
        'name': 'Tom',
        'age': 18,
        'score':
            {
                'math': 98,
                'chinese': 99
            }
    }
with open("res.jsonl", 'w', encoding='utf-8') as fw:
      json.dump(tesdic, fw, indent=4, ensure_ascii=False)


#读取json
with open("res.json", 'r', encoding='utf-8') as fw:
    newdict = json.load(fw)
    print(newdict)

json与jsonl的区别在于jsonl没有list只有并行的dict之间用"\n"分割,这也代表jsonl可以一行一行读取。反应在代码上可以看到下图中报错,JSON standard allows only one top-level value。其原因就是json格式的文件里面要求只能有一个{ },或者[ ],如果要保存多个{},应该将其组合成[{},{}]格式

更改为下图中的形式即可解决。

另一种方式就是使用jsonline:

    import jsonline
    with jsonlines.open('../output.jsonl', mode='a') as writer:
        writer.write(dict)
物联沃分享整理
物联沃-IOTWORD物联网 » Python实现写入json和jsonl文件操作方法详解

发表评论