Skip to content

Instantly share code, notes, and snippets.

@174n
Last active April 13, 2019 11:59
Show Gist options
  • Save 174n/913c92b71bec505540db697b17f3f85f to your computer and use it in GitHub Desktop.
Save 174n/913c92b71bec505540db697b17f3f85f to your computer and use it in GitHub Desktop.
const json2xml = json =>
Object.keys(json)
.map(k =>
typeof json[k] === "object" && k !== "_attr"
? `<${k +
(json[k]["_attr"]
? " " + Object.keys(json[k]["_attr"]).map(
a => `${a}="${json[k]["_attr"][a]}"`
).join(" ")
: "")
}>${json2xml(json[k])}</${k}>`
: typeof json[k] === "string"
? `<${k}>${json[k]}</${k}>`
: ""
).join("");
const json2xml=t=>Object.keys(t).map(o=>"object"==typeof t[o]&&"_attr"!==o?`<${o+(t[o]._attr?" "+Object.keys(t[o]._attr).map($=>`${$}="${t[o]._attr[$]}"`).join(" "):"")}>${json2xml(t[o])}</${o}>`:"string"==typeof t[o]?`<${o}>${t[o]}</${o}>`:"").join("");
const json2xml=t=>Object.keys(t).map(o=>"object"==typeof t[o]&&"_attr"!==o?`<${o+(t[o]._attr?" "+Object.keys(t[o]._attr).map($=>`${$}="${t[o]._attr[$]}"`).join(" "):"")}>${json2xml(t[o])}</${o}>`:"string"==typeof t[o]?`<${o}>${t[o]}</${o}>`:"").join("");export default json2xml;
@174n
Copy link
Author

174n commented Apr 13, 2019

Example:

<script type="module">
  import json2xml from "https://gistcdn.githack.com/Rundik/913c92b71bec505540db697b17f3f85f/raw/f8ae0786b2eff6876df650183655e7f624b7b4d8/json2xml.module.js";

  var xml = json2xml({
    iq: {
      _attr: {to: "marlowe.shakespeare.lit", type: "set"},
      query: {
        _attr: {xmlns: "jabber:iq:register"},
        username: "juliet",
        password: "R0m30"
      }
    }
  })
   
  console.log(xml);
  // Output:
  // <iq to="marlowe.shakespeare.lit" type="set"><query xmlns="jabber:iq:register"><username>juliet</username><password>R0m30</password></query></iq>
</script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment