kahwee / dom2json

Converts XML to JSON
ISC License
1 stars 0 forks source link
json xml

dom2json

Greenkeeper badge

This converts DOM documents into a special blend of JSON. It was intended to be used for XML and now made to be generic to accomodate HTML documents as well. Please take a look at usage examples to see if it suits your needs.

Build Status Coverage Status npm version bitHound Overall Score

Support

What is sacrificed?

In order for easy access to element node children, elements are grouped together.

For example, the following XML:

<Drinks>
  <Coffee>Latte</Coffee>
  <Tea>Chai</Tea>
  <Coffee>Mocha</Coffee>
  <Coffee>Espresso</Coffee>
  <Coffee>Flat White</Coffee>
  <Tea>Mint</Tea>
</Drinks>

Gets converted to:

{
  "document": {
    "Drinks": {
      "Coffee": [
        { $value: "Latte" },
        { $value: "Mocha" },
        { $value: "Espresso" },
        { $value: "Flat White" }
      ],
      "Tea": [
        { $value: "Chai" },
        { $value: "Mint" }
      ]
    }
  }
}

So there are some information loss here. Please use with caution!

Usage example

// Optional:
// const DOMParser = require('xmldom').DOMParser

const dp = new DOMParser()
let xml = dp.parseFromString(`<?xml version="1.0" encoding="UTF-8" standalone="no"?>
  <Hello one="1" two="2" three="3"><Hi class="a"><h1>Hello World</h1></Hi><Hi class="a">Hello again</Hi></Hello>`, 'text/xml')
result = dom2json(xml)

Results:

{
  "document":{
    "Hello":{
      "Hi":[
        {
          "h1":[
            {
              "$attrs": {
              },
              "$value": "Hello World"
            }
          ],
          "$attrs":{
            "class": "a"
          },
          "$value": "Hello World"
        },
        {
          "$attrs":{
            "class": "a"
          },
          "$value": "Hello again"
        }
      ],
      "$attrs":{
        "one":"1",
        "two":"2",
        "three":"3"
      }
    }
  }
}