JSON to XML Using Javascript

前端 未结 6 941
南旧
南旧 2020-12-11 09:25

I am trying to convert the JSON to XML but not getting exact output.In My JSON having array object it not converting that to XML array.Mainly array object is not converti

6条回答
  •  温柔的废话
    2020-12-11 10:06

    There are a few problems here, for starters, here the JSON string variable either needs to have it's quotes escaped. Or be wrapped in single quotes. For example:

    var InputJSON = '{"body":{"entry": [{ "fullURL" : "abcd","Resource": "1234"},{ "fullURL" : "efgh","Resource": "5678"}]}}';
    

    Next, there is no need to use eval here, when using JSON in JavaScript you should use JSON.parse

    // First parse the JSON
    var InputJSON = JSON.parse(InputJSON);
    
    // Now execute the 'OBJtoXML' function
    var output = OBJtoXML(InputJSON);
    

    Now we come to the meat of this question, why is entry only occuring once? The problem that you're having is that xml += "<" + prop + ">"; and xml += ""; are only happening once per property. A possible solution would look like this:

    function OBJtoXML(obj) {
        var xml = '';
        for (var prop in obj) {
            xml += "<" + prop + ">";
            if(Array.isArray(obj[prop])) {
                for (var array of obj[prop]) {
    
                    // A real botch fix here
                    xml += "";
                    xml += "<" + prop + ">";
    
                    xml += OBJtoXML(new Object(array));
                }
            } else if (typeof obj[prop] == "object") {
                xml += OBJtoXML(new Object(obj[prop]));
            } else {
                xml += obj[prop];
            }
            xml += "";
        }
        var xml = xml.replace(/<\/?[0-9]{1,}>/g,'');
        return xml
    }
    

提交回复
热议问题