从Python的字典创建JSON对象

时间:2020-10-28 08:00:09

标签: python json

以下代码用于创建JSON。 但是我在JSON中有\。

"[{\"1_245_183_424_225_251_188_416_219_SJA4549J.jpeg\": {\"fileref\": \"\", \"size\": 0, \"filename\": \"1_245_183_424_225_251_188_416_219_SJA4549J.jpeg\", \"file_attributes\": {}, \"regions\": {\"plate\": {\"shape_attributes\": {\"name\": \"polygon\", \"all_points_x\": [], \"all_points_y\": []}, \"region_attributes\": {\"width\": 720, \"height\": 720, \"depth\": 3}}}}}, {\"1_245_183_424_225_251_188_416_219_SJA4549J.jpeg\": {\"fileref\": \"\", \"size\": 0, \"filename\": \"1_245_183_424_225_251_188_416_219_SJA4549J.jpeg\", \"file_attributes\": {}, \"regions\": {\"textline\": {\"shape_attributes\": {\"name\": \"polygon\", \"all_points_x\": [], \"all_points_y\": []}, \"region_attributes\": {\"width\": 720, \"height\": 720, \"depth\": 3}}}}}, {\"IMG_20200214_081450.jpeg\": {\"fileref\": \"\", \"size\": 0, \"filename\": \"IMG_20200214_081450.jpeg\", \"file_attributes\": {}, \"regions\": {\"plate\": {\"shape_attributes\": {\"name\": \"polygon\", \"all_points_x\": [], \"all_points_y\": []}, \"region_attributes\": {\"width\": 720, \"height\": 720, \"depth\": 3}}}}}, {\"IMG_20200214_081450.jpeg\": {\"fileref\": \"\", \"size\": 0, \"filename\": \"IMG_20200214_081450.jpeg\", \"file_attributes\": {}, \"regions\": {\"plate\": {\"shape_attributes\": {\"name\": \"polygon\", \"all_points_x\": [], \"all_points_y\": []}, \"region_attributes\": {\"width\": 720, \"height\": 720, \"depth\": 3}}}}}, {\"IMG_20200214_081450.jpeg\": {\"fileref\": \"\", \"size\": 0, \"filename\": \"IMG_20200214_081450.jpeg\", \"file_attributes\": {}, \"regions\": {\"textline\": {\"shape_attributes\": {\"name\": \"polygon\", \"all_points_x\": [], \"all_points_y\": []}, \"region_attributes\": {\"width\": 720, \"height\": 720, \"depth\": 3}}}}}, {\"IMG_20200214_081450.jpeg\": {\"fileref\": \"\", \"size\": 0, \"filename\": \"IMG_20200214_081450.jpeg\", \"file_attributes\": {}, \"regions\": {\"textline\": {\"shape_attributes\": {\"name\": \"polygon\", \"all_points_x\": [], \"all_points_y\": []}, \"region_attributes\": {\"width\": 720, \"height\": 720, \"depth\": 3}}}}}]"

然后在打印到JSON文件时,文件的末尾也有“ [开头和]”。 为什么我在JSON文件的开头和结尾都带有那些?如何删除?

代码如下。

import os
import xml.etree.ElementTree as ET
import pickle
from os import listdir, getcwd
from os.path import join
import numpy as np
import cv2
import math
import random
import json
xmlspath="/home/itc/Data/NumberPlate/PlateDetection/annotations/xmls/"


xmlFiles = [f for f in listdir(xmlspath) if f.endswith("." + "xml")];
num_objs = 0
iou = 0.0
num_hits = 0
train = []
val = []
for idx,xmlFile in enumerate(xmlFiles):
   if(idx > 10):
      break
   tree = ET.parse(xmlspath+xmlFile)
   root = tree.getroot()
   filename = xmlFile.split(".")[0]+".jpeg"
   size = root.find("size")
   width = int(size.find("width").text)
   height = int(size.find("height").text)
   depth = int(size.find("depth").text)
   for obj in root.iter("object"):
      newitem={
  "name":{"fileref":"","size":0,"filename":"","file_attributes":{},"regions":{"attribute":{"shape_attributes":{"name":"polygon","all_points_x":[],"all_points_y":[]},"region_attributes":{"width":0,"height":0,"depth":3}}}}  
}
      newitem[filename]=newitem.pop("name")
      newitem[filename]["filename"]=filename
      bndbox = obj.find("bndbox")
      category = obj.find("name")
      xmin=int(bndbox.find("xmin").text)
      ymin=int(bndbox.find("ymin").text)
      xmax=int(bndbox.find("xmax").text)
      ymax=int(bndbox.find("ymax").text)
      if(obj.find("name").text == "plate"):
         newitem[filename]["regions"]["plate"] = newitem[filename]["regions"].pop("attribute")
         newitem[filename]["regions"]["plate"]["region_attributes"]["width"]=width
         newitem[filename]["regions"]["plate"]["region_attributes"]["height"]=height  
      elif(obj.find("name").text == "textline"):
         newitem[filename]["regions"]["textline"] = newitem[filename]["regions"].pop("attribute")
         newitem[filename]["regions"]["textline"]["region_attributes"]["width"]=width
         newitem[filename]["regions"]["textline"]["region_attributes"]["height"]=height                  
      if(idx%8 == 0):
         val.append(newitem)
      else:
         train.append(newitem)
      print(idx)
      

jsontrain = json.dumps(train)
jsonval = json.dumps(val)
with open("numplate/train/train.json", "w") as outfile:
    json.dump(jsontrain, outfile)
with open("numplate/val/val.json", "w") as outfile:
    json.dump(jsonval, outfile)
      
      

1 个答案:

答案 0 :(得分:1)

之所以具有“ [在文件的开头,而在文件末尾是]” 的原因是,因为您的对象(火车)是列表(而不是字典)

首先,您必须转换它们:

train = {"items" : train}
val =  = {"items" : val}

然后,对于您的编码问题,您可以通过将json.dump()设置为ensure_ascii来强制False函数不添加“”符号:

with open("numplate/train/train.json", 'w', encoding='utf8') as outfile:
    json.dump(train, outfile, ensure_ascii=False)