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)