Convert XML to JSON (and back) using Javascript

后端 未结 12 1329
Happy的楠姐
Happy的楠姐 2020-11-22 03:18

How would you convert from XML to JSON and then back to XML?

The following tools work quite well, but aren\'t completely consistent:

  • xml2json
相关标签:
12条回答
  • 2020-11-22 03:35

    I was using xmlToJson just to get a single value of the xml.
    I found doing the following is much easier (if the xml only occurs once..)

    let xml =
    '<person>' +
      ' <id>762384324</id>' +
      ' <firstname>Hank</firstname> ' +
      ' <lastname>Stone</lastname>' +
    '</person>';
    
    let getXmlValue = function(str, key) {
      return str.substring(
        str.lastIndexOf('<' + key + '>') + ('<' + key + '>').length,
        str.lastIndexOf('</' + key + '>')
      );
    }
    
    
    alert(getXmlValue(xml, 'firstname')); // gives back Hank

    0 讨论(0)
  • 2020-11-22 03:40

    A while back I wrote this tool https://bitbucket.org/surenrao/xml2json for my TV Watchlist app, hope this helps too.

    Synopsys: A library to not only convert xml to json, but is also easy to debug (without circular errors) and recreate json back to xml. Features :- Parse xml to json object. Print json object back to xml. Can be used to save xml in IndexedDB as X2J objects. Print json object.

    0 讨论(0)
  • 2020-11-22 03:45

    I think this is the best one: Converting between XML and JSON

    Be sure to read the accompanying article on the xml.com O'Reilly site, which goes into details of the problems with these conversions, which I think you will find enlightening. The fact that O'Reilly is hosting the article should indicate that Stefan's solution has merit.

    0 讨论(0)
  • 2020-11-22 03:46

    I've created a recursive function based on regex, in case you don't want to install library and understand the logic behind what's happening:

    const xmlSample = '<tag>tag content</tag><tag2>another content</tag2><tag3><insideTag>inside content</insideTag><emptyTag /></tag3>';
    console.log(parseXmlToJson(xmlSample));
    
    function parseXmlToJson(xml) {
        const json = {};
        for (const res of xml.matchAll(/(?:<(\w*)(?:\s[^>]*)*>)((?:(?!<\1).)*)(?:<\/\1>)|<(\w*)(?:\s*)*\/>/gm)) {
            const key = res[1] || res[3];
            const value = res[2] && parseXmlToJson(res[2]);
            json[key] = ((value && Object.keys(value).length) ? value : res[2]) || null;
    
        }
        return json;
    }

    Regex explanation for each loop:

    • res[0] - return the xml (as is)
    • res[1] - return the xml tag name
    • res[2] - return the xml content
    • res[3] - return the xml tag name in case the tag closes itself. In example: <tag />

    You can check how the regex works here: https://regex101.com/r/ZJpCAL/1

    Note: In case json has a key with an undefined value, it is being removed. That's why I've inserted null at the end of line 9.

    0 讨论(0)
  • 2020-11-22 03:49

    In 6 simple ES6 lines:

    xml2json = xml => {                                                                                                                                                     
      var el = xml.nodeType === 9 ? xml.documentElement : xml                                                                                                               
      var h  = {name: el.nodeName}                                                                                                                                          
      h.content    = Array.from(el.childNodes || []).filter(e => e.nodeType === 3).map(e => e.textContent).join('').trim()                                                  
      h.attributes = Array.from(el.attributes || []).filter(a => a).reduce((h, a) => { h[a.name] = a.value; return h }, {})                                                 
      h.children   = Array.from(el.childNodes || []).filter(e => e.nodeType === 1).map(c => h[c.nodeName] = xml2json(c))                                                    
      return h                                                                                                                                                              
    }  
    

    Test with echo "xml2json_example()" | node -r xml2json.es6 with source at https://github.com/brauliobo/biochemical-db/blob/master/lib/xml2json.es6

    0 讨论(0)
  • 2020-11-22 03:50

    Here' a good tool from a documented and very famous npm library that does the xml <-> js conversions very well: differently from some (maybe all) of the above proposed solutions, it converts xml comments also.

    var obj = {name: "Super", Surname: "Man", age: 23};
    
    var builder = new xml2js.Builder();
    var xml = builder.buildObject(obj);
    
    0 讨论(0)
提交回复
热议问题