在处理XML转换为JSON时,遇到了Unicode编码的问题。可以使用decode方法将Unicode编码转换为字符串。

修改代码如下:

def xml_to_json(file_path):
    tree = ET.parse(file_path)
    root = tree.getroot()
    data = {}

    for child in root:
        if child.tag == 'short':
            data['short'] = child.text
        elif child.tag == 'description':
            data['description'] = child.text.decode('unicode_escape')
        elif child.tag == 'port':
            data['port'] = child.attrib['port']
        elif child.tag == 'protocol':
            data['protocol'] = child.text

    return data

通过使用decode('unicode_escape')方法,可以将Unicode编码转换为字符串。这样返回的值就会是正确的文字了

def xml_to_jsonfile_path tree = ETparsefile_path root = treegetroot data = for child in root if childtag == short datashort = childtext elif childtag == descripti

原文地址: https://www.cveoy.top/t/topic/ihyW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录