单个Json文件数据集转xml格式

本文介绍了一个Python脚本,用于将单个包含所有标注信息的JSON文件转换为XML格式,仅保留除name以外的数据,并为每个XML文件命名。脚本适用于数据集标注文件的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单个Json文件数据集转xml格式

  • 如果你下载的数据集标注文件是 json格式,且全部在一个json文件中,就用这个代码
  • 只需要修改两处路径!
# Continue to write the Python script to convert the JSON to XML using the 'name' as the file name for each XML.
import os
import xml.etree.ElementTree as ET
import json

# 用你的 JSON 文件路径替换这里的路径
with open(r'C:\Users\lenovo\Desktop\anno_train.json', 'r', encoding='utf-8') as file:
    data = json.load(file)


def create_xml_element_from_dict(parent, dict_obj):
    """ Recursively create XML elements from dictionary keys and assign their values """
    for key, value in dict_obj.items():
        if isinstance(value, dict):  # If value is a dict, make a subelement and recurse
            sub_element = ET.SubElement(parent, key)
            create_xml_element_from_dict(sub_element, value)
        elif isinstance(value, list):  # If value is a list, create a subelement for each item
            for item in value:
                sub_element = ET.SubElement(parent, key)
                sub_element.text = str(item)
        else:  # If value is neither dict nor list, just assign the value
            sub_element = ET.SubElement(parent, key)
            sub_element.text = str(value)


def json_to_xml_file(json_obj, directory):
    """ Takes a JSON object and creates an XML file with a specific name """
    # Create a root element
    root = ET.Element('annotation')

    # Exclude 'name' from the XML structure; use it only for the file name
    json_obj_except_name = {k: v for k, v in json_obj.items() if k != 'name'}

    # Create XML elements from dictionary
    create_xml_element_from_dict(root, json_obj_except_name)

    # Convert to a string of XML
    xml_str = ET.tostring(root, encoding='unicode')

    # Define the file path
    file_name = f"{json_obj['name'].split('.')[0]}.xml"  # Using name value without file extension
    file_path = os.path.join(directory, file_name)

    # Save to file
    with open(file_path, 'w') as file:
        file.write(xml_str)


# Now let's create the XML files using the JSON data
# xml_directory修改为存储xml文件路径,xml_files_with_names不要修改!!!
xml_directory = 'E:/Py/yolo/data_xml/xml_files_with_names'  # Define the directory to save XML files
os.makedirs(xml_directory, exist_ok=True)  # Create the directory if it does not exist

# Generate XML files
for json_obj in data:
    json_to_xml_file(json_obj, xml_directory)

# Check if the files were created properly
created_files = os.listdir(xml_directory)
# created_files[:5]  # Display the first 5 file names as a check

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值