javascript SOAP 响应 (XML) 到 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17314185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:51:26  来源:igfitidea点击:

SOAP response (XML) to JSON

javascriptxmljsonsoaptitanium

提问by JonoCoetzee

I need to consume a SOAP web service which, naturally, sends its response in XML, since I'm developing a Appcelerator Titanium mobile app I would prefer the response in JSON. After looking online I converted the response using thisJavascript code, it mostly worked but returned results such as the following:

我需要使用 SOAP Web 服务,该服务自然会以 XML 格式发送响应,因为我正在开发 Appcelerator Titanium 移动应用程序,因此我更喜欢 JSON 格式的响应。在线查看后,我使用Javascript 代码转换了响应,它主要工作但返回的结果如下:

{
    "SOAP-ENV:Body" :     {
        "ns1:linkAppResponse" :         {
            "ns1:result" :             {
                #text : true;
            };
            "ns1:uuid" :             {
                #text : "a3dd915e-b4e4-43e0-a0e7-3c270e5e7aae";
            };
        };
    };
}

Of course the colons and hashes in the caused problems so I adjusted the code to do a substring on the name and drop off anything before the ':', then a stringified the resulting JSON, removed all the hashes and parsed the JSON again. This is a bit messy for my liking but I end up with something usable.

当然,冒号和散列会导致问题,所以我调整了代码以在名称上做一个子字符串并在“:”之前删除任何内容,然后对生成的 JSON 进行字符串化,删除所有散列并再次解析 JSON。这对我来说有点凌乱,但我最终得到了一些可用的东西。

Here is the xmlToJson code I'm using:

这是我正在使用的 xmlToJson 代码:

// Changes XML to JSON
function xmlToJson(xml) {

    // Create the return object
    var obj = {};

    if (xml.nodeType == 1) {// element
        // do attributes
        if (xml.attributes.length > 0) {
            obj["@attributes"] = {};
            for (var j = 0; j < xml.attributes.length; j++) {
                var attribute = xml.attributes.item(j);
                obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
            }
        }
    } else if (xml.nodeType == 3) {// text
        obj = xml.nodeValue;
    }

    // do children
    if (xml.hasChildNodes()) {
        for (var i = 0; i < xml.childNodes.length; i++) {
            var item = xml.childNodes.item(i);
            var nodeName = item.nodeName.substring(item.nodeName.indexOf(":") + 1);
            if ( typeof (obj[nodeName]) == "undefined") {
                obj[nodeName] = xmlToJson(item);
            } else {
                if ( typeof (obj[nodeName].push) == "undefined") {
                    var old = obj[nodeName];
                    obj[nodeName] = [];
                    obj[nodeName].push(old);
                }
                obj[nodeName].push(xmlToJson(item));
            }
        }
    }
    return obj;
};

module.exports = xmlToJson; 

Which results in the following JSON:

这会产生以下 JSON:

{
    Body :     {
        linkAppResponse :         {
            result :             {
                text : true;
            };
            uuid :             {
                text : "9022d249-ea8a-47a3-883c-0f4cfc9d6494";
            };
        };
    };
}

While this returns a JSON object I can use, I would prefer to have the resulting JSON in the following form:

虽然这会返回一个我可以使用的 JSON 对象,但我更希望生成的 JSON 格式如下:

{
    result : true;
    uuid : "9022d249-ea8a-47a3-883c-0f4cfc9d6494";
};

Mostly so it's less verbose and I can simply call json.result in order check if the query was successful instead of json.Body.linkAppResponse.result.text

大多数情况下它不那么冗长,我可以简单地调用 json.result 来检查查询是否成功而不是 json.Body.linkAppResponse.result.text

Any help is greatly appreciated.

任何帮助是极大的赞赏。

回答by JonoCoetzee

Came up with a working solution, not any less dirty but it works and returns data in the format I want.

提出了一个可行的解决方案,虽然不那么脏,但它可以工作并以我想要的格式返回数据。

function soapResponseToJson(xml) {
    var json = xmlToJson(xml).Body;

    console.debug(json);

    var response = {};
    for (var outterKey in json) {
        if (json.hasOwnProperty(outterKey)) {
            temp = json[outterKey];
            for (var innerKey in temp) {
                if (temp.hasOwnProperty(innerKey)) {
                    response[innerKey] = temp[innerKey].text;
                }
            }
        }
    }

    console.debug(response);
    return response;
}

// Changes XML to JSON
function xmlToJson(xml) {

    // Create the return object
    var obj = {};

    if (xml.nodeType == 1) {// element
        // do attributes
        if (xml.attributes.length > 0) {
            obj["@attributes"] = {};
            for (var j = 0; j < xml.attributes.length; j++) {
                var attribute = xml.attributes.item(j);
                obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
            }
        }
    } else if (xml.nodeType == 3) {// text
        obj = xml.nodeValue;
    }

    // do children
    if (xml.hasChildNodes()) {
        for (var i = 0; i < xml.childNodes.length; i++) {
            var item = xml.childNodes.item(i);
            var nodeName = item.nodeName.substring(item.nodeName.indexOf(":") + 1).replace('#', '');
            if ( typeof (obj[nodeName]) == "undefined") {
                obj[nodeName] = xmlToJson(item);
            } else {
                if ( typeof (obj[nodeName].push) == "undefined") {
                    var old = obj[nodeName];
                    obj[nodeName] = [];
                    obj[nodeName].push(old);
                }
                obj[nodeName].push(xmlToJson(item));
            }
        }
    }
    return obj;
};

module.exports = soapResponseToJson;

console.debug(json):

控制台调试(json):

{
    linkAppResponse :     {
        result :         {
            text : true;
        };
        uuid :         {
            text : "e4f78c5f-1bc2-4b50-a749-19d733b9be3f";
        };
    };
}

console.debug(response):

控制台调试(响应):

{
    result : true;
    uuid : "e4f78c5f-1bc2-4b50-a749-19d733b9be3f";
}

I'm going to leave this question open for a while in case someone comes up with a better solution.

如果有人想出更好的解决方案,我将暂时搁置这个问题。