JSON to XML Using Javascript

前端 未结 6 945
南旧
南旧 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:00
    function OBJtoXML(obj, index) {
        var xml = '', 
            root, 
            count = 0;
        if (index > 0) count = index;
        for (var prop in obj) {
          switch (typeof obj[prop]) {
              case 'object': {
                  if(obj[prop] instanceof Array) {
                      for (var instance in obj[prop]) {
                        xml += `\n\t<${prop}>\n${OBJtoXML(new Object(obj[prop][instance]))}\t</${prop}>`;
                      }
                  }
                  else {
                      if (count === 0) {
                        // console.log(`Setting root: ${prop}`)
                        root = prop
                      }
                      xml += `<${prop}>${OBJtoXML(new Object(obj[prop]), count)}\n</${prop}>\n`;
                  }
                  break;
              }
              case 'number':
              case 'string': {
                  // console.log(`Setting ${typeof obj[prop]}`)
                  xml += `\t\t<${prop}>${obj[prop]}</${prop}>\n`;
                  break;
              }
          }
          count += 1;
        }
        return xml
    }
    
    var InputJSON = '{"body":{"entry": [{ "fullURL" : "abcd","Resource": "1234"},{ "fullURL" : "efgh","Resource": "5678"}]}}';
    var output = eval("OBJtoXML("+InputJSON+");");
    console.log(output);
    
    0 讨论(0)
  • 2020-12-11 10:03

    Xml-to-json library has method jsonToXml(json). I am the maintainer of the project.

    var inputJSON = '{"body":{"entry": [{ "fullURL" : "abcd","Resource": "1234"},{ "fullURL" : "efgh","Resource": "5678"}]}}';
    
    var xml = jsonToXml(inputJSON);
    
    // <?xml version="1.0" encoding="UTF-8"?>
    // <body>
    //   <entry>
    //     <fullURL>abcd</fullURL>
    //     <Resource>1234</Resource>
    //   </entry>
    //   <entry>
    //     <fullURL>efgh</fullURL>
    //     <Resource>5678</Resource>
    //   </entry>
    // </body>
    
    0 讨论(0)
  • 2020-12-11 10:04

    replace your OBJtoXML function with

    function OBJtoXML(obj) {
      var xml = '';
      for (var prop in obj) {
        xml += obj[prop] instanceof Array ? '' : "<" + prop + ">";
        if (obj[prop] instanceof Array) {
          for (var array in obj[prop]) {
            xml += "<" + prop + ">";
            xml += OBJtoXML(new Object(obj[prop][array]));
            xml += "</" + prop + ">";
          }
        } else if (typeof obj[prop] == "object") {
          xml += OBJtoXML(new Object(obj[prop]));
        } else {
          xml += obj[prop];
        }
        xml += obj[prop] instanceof Array ? '' : "</" + prop + ">";
      }
      var xml = xml.replace(/<\/?[0-9]{1,}>/g, '');
      return xml
    }
    
    0 讨论(0)
  • 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 += "</" + prop + ">"; 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 += "</" + prop + ">";
                    xml += "<" + prop + ">";
    
                    xml += OBJtoXML(new Object(array));
                }
            } else if (typeof obj[prop] == "object") {
                xml += OBJtoXML(new Object(obj[prop]));
            } else {
                xml += obj[prop];
            }
            xml += "</" + prop + ">";
        }
        var xml = xml.replace(/<\/?[0-9]{1,}>/g,'');
        return xml
    }
    
    0 讨论(0)
  • 2020-12-11 10:11
    const objectToXml = (object) => Object.keys(object).reduce((reqStr, key) => {
      const value = object[key] || '';
      const isObject = typeof value === 'object';
      const isArray = Array.isArray(value);
      if (isArray) {
        return reqStr + value.reduce((accumulator, currentValue) =>
          accumulator + `<${key}>${ typeof currentValue === 'object' ? objectToXml(currentValue) : (currentValue || '')}</${key}>`
        ,'');
      }
      if (isObject) {
        return reqStr + `<${key}>${objectToXml(value)}</${key}>`;
      }
      return reqStr + `<${key}>${value}</${key}>`;
    }, '');       
    
    const output = objectToXml(yourJson);
    console.log(output);
    
    0 讨论(0)
  • 2020-12-11 10:18
    var inputJSON = '{"body":{"entry": [{ "fullURL" : "abcd","Resource": "1234"},{ "fullURL" : "efgh","Resource": "5678"}]}}';
    var parsedInput = JSON.parse(inputJSON);
    
    function OBJtoXML(obj) {
        var xml = '';
        for (var prop in obj) {
            if (obj[prop] instanceof Array) {
                for (var array in obj[prop]) {
                    xml += '<' + prop + '>';
                    xml += OBJtoXML(new Object(obj[prop][array]));
                    xml += '</' + prop + '>';
                }
            } else {
                xml += '<' + prop + '>';
                typeof obj[prop] == 'object' ? xml += OBJtoXML(new Object(obj[prop])) : xml += obj[prop];
                xml += '</' + prop + '>';
            }
        }
        var xml = xml.replace(/<\/?[0-9]{1,}>/g, '');
        return xml;
    }
    
    0 讨论(0)
提交回复
热议问题