python:向json里面追加数据

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)

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

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
心中带点小风骚的头像心中带点小风骚普通用户
上一篇 2023年3月11日
下一篇 2023年3月11日

相关推荐