json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)原来是因为放.json的文件夹内混入了.py文件
说来也是蠢,挑了150张图片json转txt没有任何问题,大批量转的时候就发现有一部分没有转成功,报json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)的错,
上网搜多是说单引号引起的或者html需要先转一下,而我显然不存在这样的问题,于是打印了一下中间代码,
发现读到an_2021-06-2021_13_58.py时出错了,原来是放.json的文件夹里混进了一个.py文件!!!导致报错……所以实在查不出哪里错了,也可以检查下会不会是因为这个原因。
import json
import os
def convert(img_size, box):
x1 = box[0]
y1 = box[1]
x2 = box[2]
y2 = box[3]
return (x1, y1, x2, y2)
def decode_json(json_floder_path, json_name):
txt_name = './txt/'+json_name[0:-5] + '.txt' #生成txt文件你想存放的路径
txt_file = open(txt_name, 'w',encoding='utf-8')
json_path = os.path.join(json_floder_path, json_name)#os.path.join(path1[, path2[, ...]]) 把目录和文件名合成一个路径
data = json.load(open(json_path, 'r',encoding='utf-8'))
img_w = data['imageWidth']
img_h = data['imageHeight']
#wqe = data['imagePath']
for i in data['shapes']:
if (i['shape_type'] == 'rectangle' and i['label'] == 'corner'): #分类的标签
x1 = float((i['points'][0][0]))/img_w
y1 = float((i['points'][0][1]))/img_h
x2 = float((i['points'][1][0]))/img_w
y2 = float((i['points'][1][1]))/img_h
bb = (x1, y1, x2, y2)
bbox = convert((img_w, img_h), bb)
txt_file.write( '0' + " " + " ".join([str(a) for a in bbox]) + '\n')
if (i['shape_type'] == 'rectangle' and i['label'] == 'midlineh'): #分类的标签
x1 = float((i['points'][0][0]))/img_w
y1 = float((i['points'][0][1]))/img_h
x2 = float((i['points'][1][0]))/img_w
y2 = float((i['points'][1][1]))/img_h
bb = (x1, y1, x2, y2)
bbox = convert((img_w, img_h), bb)
txt_file.write( '1' + " " + " ".join([str(a) for a in bbox]) + '\n')
if __name__ == "__main__":
json_floder_path = './json1234' #json文件的路径
json_names = os.listdir(json_floder_path)#os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表。
for json_name in json_names:
decode_json(json_floder_path, json_name)