首页 > 解决方案 > 使用 xmltodict 解析器对 json api 进行编码

问题描述

api 工作正常,但是当我尝试用包含特殊字符(如“pé”)的 char 值填充 package_description 字段时,会出现验证错误,我正在使用 xmltodict 库从 xml 文件中解析

这是我的代码

PS我正在使用python2.7

payload = "".join(
    [
            (self.name),
            self.tag_end("code"),
            (self.description_package or ""),
            self.tag_end("description"),
            self.new_line(),
            self.get_tab(),
            self.sub_tag_start("dateModification"),
            self.tag_end("motif"),
            self.new_line(),
            self.get_tab(),
            self.tag_end("package"),
        ]
    )

    response = requests.request("POST", url, headers=headers, data=payload)


    res = json.loads(
        json.dumps(xmltodict.parse(response.text, encoding='utf-8', process_namespaces=True))
    )
    if response.status_code != 200:
        message = ""
        description = ""
        guid = ""
        res = json.loads(
            json.dumps(xmltodict.parse(response.text, encoding='utf-8', process_namespaces=True))
        )
        if (
            res
            and res.get("http://www.web.com/something:reponse")
            and res.get("http://www.web.com/something:reponse").get(
                "http://www.web.com/something:description"
            )
        ):
            message = res["http://www.web.com/something:reponse"][
                "http://www.web.com/something:message"
            ]
            description = res["http://www.web.com/something:reponse"][
                "http://www.web.com/something:description"
            ]
            guid = res["http://www.web.com/something:reponse"][
                "http://www.web.com/something:guid"
            ]
        _logger.warning("\nERROR MESSAGE: \n\n %s \n\n" % str(response.text))
        raise ValidationError(
            "%s \n\n %s \nGUID: %s" % (message, description, guid)
        )

标签: pythonpython-2.7apixmltodict

解决方案


推荐阅读