https://github.com/kahwee/dom2json
Converts XML to JSON
https://github.com/kahwee/dom2json
json xml
Last synced: about 1 month ago
JSON representation
Converts XML to JSON
- Host: GitHub
- URL: https://github.com/kahwee/dom2json
- Owner: kahwee
- License: isc
- Created: 2016-01-10T22:02:39.000Z (over 10 years ago)
- Default Branch: master
- Last Pushed: 2020-05-23T12:15:19.000Z (about 6 years ago)
- Last Synced: 2025-10-26T11:42:45.831Z (8 months ago)
- Topics: json, xml
- Language: JavaScript
- Homepage:
- Size: 116 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 21
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# dom2json
[](https://greenkeeper.io/)
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.
[](https://travis-ci.org/kahwee/dom2json)
[](https://coveralls.io/github/kahwee/dom2json?branch=master)
[](https://badge.fury.io/js/dom2json)
[](https://www.bithound.io/github/kahwee/dom2json)
## Support
* Browser (tested on Firefox)
* `xmldom`
## What is sacrificed?
In order for easy access to element node children, elements are grouped together.
For example, the following XML:
```xml
Latte
Chai
Mocha
Espresso
Flat White
Mint
```
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
```js
// Optional:
// const DOMParser = require('xmldom').DOMParser
const dp = new DOMParser()
let xml = dp.parseFromString(`
Hello World
Hello again`, 'text/xml')
result = dom2json(xml)
```
Results:
```json
{
"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"
}
}
}
}
```