首页 > 解决方案 > 从 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)
      
      

标签: pythonjson

解决方案


你有 “[开头和文件结尾]”的原因是因为你的对象(val火车)是列表(不是字典)

首先你必须转换它们:

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

然后,对于您的编码问题,您可以通过设置to来强制json.dump()函数不添加 "" 符号:ensure_asciiFalse

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

推荐阅读