场景:在使用了mask rcnn跑实验后标注了大量地json格式文件,现在打算使用yolo和faster rcnn 跑实验 所以需要将之前地json文件转为xml
但是找了很久,没发现有批量处理的代码,所以自己写了一个,经测可用。
使用方法:将我代码拷贝入一个python文件中;修改34和35行对应参数json_path和xml_path,分别代表要转的json文件主目录(有json文件的上一级目录)和xml文件存放目录
ps:前面加r是表示取消转义符 下附代码 ====
1
#
--------------------------------------------------------
2
#
Written by JianFeng Liu, based on python
3
#
json file transform to xml file automatically
4
#
--------------------------------------------------------
5
import
xmltodict
6
import
json
7
import
os
8
9
#
json to xml
10
def
jsonToXml(json_str):
11
try
:
12
xml_str=
""
13
xml_str = xmltodict.unparse(json_str, encoding=
'
utf-8
'
)
14
except
:
15
xml_str = xmltodict.unparse({
'
request
'
: json_str}, encoding=
'
utf-8
'
)
16
finally
:
17
return
xml_str
18
19
def
json_to_xml(json_path,xml_path):
20
if
(os.path.exists(xml_path)==
False):
21
os.makedirs(xml_path)
22
dir =
os.listdir(json_path)
23
for
file
in
dir:
24
file_list=file.split(
"
.
"
)
25
with open(os.path.join(json_path,file),
'
r
'
) as load_f:
26
load_dict =
json.load(load_f)
27
json_result =
jsonToXml(load_dict)
28
f = open(os.path.join(xml_path,file_list[0]+
"
.xml
"
),
'
w
'
, encoding=
"
UTF-8
"
)
29
f.write(json_result)
30
f.close()
31
32
if
__name__
==
'
__main__
'
:
33
34
json_path=r
"
G:\jianfeng\project\rubblish_det\source\train_pic_json\111
"
#
该目录为存放json文件的路径 ps:目录中只能存放json文件
35
xml_path=r
"
G:\jianfeng\project\rubblish_det\source\train_pic_json\222
"
#
该目录为放xml文件的路径
36
json_to_xml(json_path,xml_path)

