python读取删除重写json以及遇见问题ValueError: No JSON object could be decoded

Problem:


ValueError: No JSON object could be decoded

Solution:

多半是json的文件内部格式有问题。需要仔细检查一下几个部分:

{"info": {"description": "This is stable 1.0 version of the 2014 MS COCO dataset.", "url": "http://mscoco.org", "version": "1.0", "year": 2014, "contributor": "Microsoft COCO group", "date_created": "2015-11-11 02:11:36.777541"}, "images": [{"license": 2, "file_name": "COCO_test2014_000000523573.jpg", "coco_url": "http://mscoco.org/images/523573", "height": 500, "width": 423, "date_captured": "2013-11-14 12:21:59", "id": 523573}, {"license": 2, "file_name": "COCO_test2014_000000347527.jpg", "coco_url": "http://mscoco.org/images/347527", "height": 480, "width": 640, "date_captured": "2013-11-14 15:12:02", "id": 347527}}}

忽视所有的 ‘>>’, ‘<<’符号 只是为了提示二者之间是重要符号,可能包括空格
1.不同的{}之间是否有>>, <<,逗号后面有一个空格
2. 标签的冒号后面有空格
3. 用python写json文件的时候尽量写入整个list,而不是把json下的某个标签下的元素逐个写入,会报错,无法读取。(eg:就是下文代码中的image2元素不可逐一写入,可以先进行del操作,最后整个list写入json文件,否则会报错)

python读取删除重写json 的代码实现

以下 是用python处理json文件的代码

def delete_special(annot_path):
    f = open('./original/'+annot_path)
    jsonfile = json.load(f)
    imagesList=[]

    imagesList = jsonfile['images']
    with open('./new2/'+annot_path,'w') as f1:
        f1.write("{\"info\": ")
        json.dump(jsonfile['info'],f1)
        f1.write(", \"images\": ")      
        # global image2
        # image2=""
        for image2 in imagesList:
            height=float(image2['height'])
            width=float(image2['width'])
            if height!=0 and width!=0:
                ratio=height/width
                ratio_c=width/height
                if ratio>0.3 and ratio<3.33:
                    pass
                else:
                    del image2
            else:
                del image2
        json.dump(imagesList,f1)                    
        f1.write(", \"licenses\": ")
        json.dump(jsonfile['licenses'],f1)
        f1.write(", \"annotations\": ")
        json.dump(jsonfile['annotations'],f1)
        f1.write(", \"categories\": ")
        json.dump(jsonfile['categories'],f1)
        f1.write("}")
    f1.close()

    print annot_path+":  write new file successfully"

if __name__ == '__main__':
    annot_path = 'image_info_test2014.json'
    delete_special(annot_path)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值