Convert XML to JSON (and back) using Javascript

后端 未结 12 1498
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: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 contentanother contentinside content';
    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:

    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.

提交回复
热议问题