python:向json里面追加数据 您所在的位置:网站首页 python向字符串添加字符 python:向json里面追加数据

python:向json里面追加数据

2023-11-01 17:29| 来源: 网络整理| 查看: 265

json以其轻量级的数据交换格式,且易于阅读和编写而使用率很广泛,而使用json的过程中时而需要增加字段,本人验证两种方式之后将其集成梳理。

具体操作详情如下:

1. list dump (不推荐)

采用list方式,向json中添加字段。此法存在一定的问题,不推荐使用。

方法如下:

(1)先创建一个列表;

json_content = []

(2)将当前json文件中已有的内容读入列表中;

with open(fjson, 'r') as f: content = json.load(f) # 读取所有字段 version = content["version"] flags = content["flags"] shapes = content["shapes"] imageData = content["imageData"] imagePath = content["imagePath"] imageHeight = content["imageHeight"] imageWidth = content["imageWidth"] item_dict = { "version": version, "flags": flags, "shapes": shapes, "imageData": imageData, "imagePath": imagePath, "imageHeight": imageHeight, "imageWidth": imageWidth } json_content.append(item_dict) # 将读取的内容append到list中

(3)将新增的内容以字典形式添加至列表中;

axis = {"axis":[22,10,33]} json_content.append(axis)

(4)使用json.dump()将该列表写回原文件;

with open(fjson, 'w') as f_new: json.dump(content, f_new)

问题:此方法采用dump list的方式追加内容,但是问题在于此法将json的dict对象转换成了list对象,会导致修改json格式,故而不推荐。

2. json update (推荐使用)

使用dict自带函数update,将字典dict对应的key/value更新到另一个dict中。

此法简单快捷,直接更新dict,而不需要将原始文件的key/value全部读取出来。

(1)读取原始json文件(与方式1相同)

with open(fjson, 'r') as f: content = json.load(f)

(2)更新字典dict

axis = {"axis":[22, 10, 11]} content.update(axis)

(3)写入

with open(fjson, 'w') as f_new: json.dump(content, f_new)

很简单,三步搞定,简单方便快捷。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有