Modify the elements in the dictionary which set in the list which set in the dictionary in JSON file

1、Generate a test JSON file

import json

json_obj = json.loads('{"one": 1, "two": 2, "annotations": [{"id":1, "image_id":1, "category_id":1, "iscrowd": 0, "area": 730361, "bbox":[0,1] },{"id": 2, "image_id": 1, "category_id": 1, "iscrowd": 0, "area": 636026, "bbox": [22.0,0]}]}')

with open('data.json', 'w') as f:
    json.dump(json_obj, f)

2、Change elements

import json

import os, sys

json_path = 'data.json'
# original json
json_path1 = 'data.json'
# Change json storage pathway 
annotations = 'annotations'
category_id = 'category_id'
dic_num = 0
category_num = 110

dict = {}



def get_json_data(json_path):

    with open(json_path, 'rb') as f:
        new_json = json.load(f)
        new_json[annotations][dic_num][category_id] = category_num
        print("new_json", new_json)
        dict = new_json
    f.close()

    return dict

def write_json_data(dict):
    with open(json_path1, 'w') as r:
        json.dump(dict, r)
    r.close()


the_revised_dict = get_json_data(json_path)
write_json_data(the_revised_dict)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值