-3

I am struggling with creating a generic function that will convert a JSON object to XML

Note: the number of columns in the headers and body may vary. Additionally, I am not interested in values in the footer

I Have the following JSON structure:

{
    "header": [ "Room", "Maximum Capacity" ],
    "footer": null,
    "body": [
        [ "Game Room", "0" ],
        [ "gymnasium", "" ],
        [ "Library", "200" ]
    ]
}

I would like to format:

<root>
  <row>
    <Room>Game Room</Room>
    <MaximumCapacity>0</MaximumCapacity>
  </row>
  <row>
    <Room>gymnasium</Room>
    <MaximumCapacity></MaximumCapacity>
  </row>
 <row>
    <Room>Library</Room>
    <MaximumCapacity>200</MaximumCapacity>
  </row>
</root>
DennisT
  • 45
  • 6
  • 2
    That's nice... but you didn't try anything yet? – trincot Oct 08 '20 at 14:02
  • 1
    Please show what research you done into the matter and what attempts you've made based on that research. There are thousands of tools and articles on converting JSON to XML and back on the internet. – Heretic Monkey Oct 08 '20 at 14:08
  • Thanks for the assistance. I have spent hours searching for a solution. So when I ask the community for assistance, this is the response I received. I would not have asked for help if I did not already try. – DennisT Oct 08 '20 at 14:34
  • I understand, but is it too much asked that you add to your question *what* you have tried, and *where* you got stuck? For your information, the tooltip on the downvote button reads "This question does not show any research effort". – trincot Oct 08 '20 at 14:56
  • [JSON to XML Using Javascript](https://stackoverflow.com/q/48788722/215552) and [Convert XML to JSON (and back) using Javascript](https://stackoverflow.com/q/1773550/215552) were found in a [simple search of Stack Overflow](https://stackoverflow.com/search?q=convert+json+to+xml+%5Bjavascript%5D) – Heretic Monkey Oct 09 '20 at 12:37

2 Answers2

1

First of all, I'll assume you've already turned that JSON to a JavaScript object.

You should convert the header values to tag names. This will involve removing spaces, but in general you may need to do more, so to avoid invalid tag names. I will just focus on the space removal here.

Then use the DOMParser API to create an XML document. That way you avoid the traps of invalid characters in your XML tag contents.

Iterate the body data and create XML nodes dynamically, based on the tag names collected from the header data.

Here is how that works:

let obj = {
    "header": [ "Room", "Maximum Capacity" ],
    "footer": null,
    "body": [
        [ "Game Room", "0" ],
        [ "gymnasium", "" ],
        [ "Library", "200" ]
    ]
};

let tagNames = obj.header.map(name => name.replace(/\s*/g, ""));
let parser = new DOMParser();
let xmlDoc = parser.parseFromString("<root></root>", "text/xml");
let root = xmlDoc.getElementsByTagName("root")[0];
for (let data of obj.body) {
    let row = xmlDoc.createElement("row");
    for (let i = 0; i < tagNames.length; i++) {
        let cell = xmlDoc.createElement(tagNames[i]);
        cell.textContent = data[i];
        row.appendChild(cell);
    }
    root.appendChild(row);
}
var xmlString = new XMLSerializer().serializeToString(xmlDoc);
console.log(xmlString);
trincot
  • 317,000
  • 35
  • 244
  • 286
0

I think this is a good challenge for you to do, so I'm not giving you a solution but just pointing out a couple of hints:

  • You can parse a JSON from string with JSON.parse
  • You can iterate over the JSON key/value pairs by using Object.entries, e.g. Object.entries(json).forEach(([key, value]) => <do the magic>);
  • You need a recursive function, because the nesting of a json (and xml) can have multiple levels. So you will probably have something like this:
function jsonToXml(json) {
  return Object.entries(json).map(([key, value]) => {
    if(isArray(value) || isObject(value)) { // TODO: Find out how to check if a variable is an array or object!
      return jsonToXml(value); // TODO: Think about on how wrap the value in the xml tag! 
    }
    return value // TODO: Think about on how wrap the value in the xml tag! 
  });
}
code-gorilla
  • 2,231
  • 1
  • 6
  • 21