Problem:
ValueError: No JSON object could be decoded
Solution:
It's mostly the internal format of json's file that's out of order. Several parts need to be examined carefully:
{"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}}}
Ignoring all'>','<'symbols are just to suggest that they are important symbols, possibly including spaces.
1. Is there a space between different {},<<, after the comma?
2. There is a space behind the colon of the label.
3. Write the json file in python as much as possible into the entire list, rather than writing the elements under a tag under json one by one, which will cause errors and can not be read. (eg: The image2 elements in the following code can not be written one by one, so del operation can be performed first, and the entire list can be written to the json file, otherwise the error will be reported.)
Code implementation of reading, deleting and rewriting json in python
Here's the code for handling json files with python
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)