Public
Edited
Jun 21, 2023
Fork of XML to JSON
Importers
Insert cell
Insert cell
parser = new DOMParser()
Insert cell
Insert cell
Insert cell
jsonObj = xmlToJSON(xmlText)
Insert cell
xmlToJSON = (src) => domToJSON(parser.parseFromString(src, "application/xml"))
Insert cell
DOM.download(
new Blob([JSON.stringify(jsonObj)], { type: "text/json" }),
"output.json",
"Save JSON"
)
Insert cell
function domToJSON(node) {
let obj = Object.create(null);
if (node.children.length === 0 && node.innerHTML) {
obj.content = node.innerHTML;
}

const counts = childCounts(node);

for (const child of node.children) {
const { localName } = child;
if (counts[localName] > 1) {
(obj[localName] = obj[localName] || []).push(domToJSON(child));
} else {
obj[localName] = domToJSON(child);
}
}

let attrs = node.attributes;
if (attrs) {
for (let i = attrs.length - 1; i >= 0; i--) {
obj[attrs[i].name] = attrs[i].value;
}
}

return obj;
}
Insert cell
childCounts = (node) => {
const counts = {};
for (const {localName} of node.children)
counts[localName] = (counts[localName] || 0) + 1;
return counts;
}
Insert cell
Insert cell
xmlToMap(`<?xml version="1.0" encoding="UTF-8" ?>
<stuff>
<count>3</count>
<person>
<name>Alice</name>
<age>1</age>
</person>
<person>
<name>Bob</name>
<age>2</age>
</person>
<person>
<name>นก</name>
<age>3</age>
</person>
</stuff>
`)
Insert cell
xmlToMap = (src) => domToMap(parser.parseFromString(src, "application/xml"))
Insert cell
function domToMap(node) {
const map = new Map();

if (node.children.length === 0 && node.innerHTML) {
map.set("content", node.innerHTML);
}
const counts = childCounts(node);

for (const child of node.children) {
const { localName } = child;
if (counts[localName] > 1) {
const array = map.get(localName) || [];
array.push(domToMap(child));
map.set(localName, array);
} else {
map.set(localName, domToMap(child));
}
}

let attrs = node.attributes;
if (attrs) {
for (let i = attrs.length - 1; i >= 0; i--) {
map.set(attrs[i].name, attrs[i].value);
}
}

return map;
}
Insert cell
// While file.inputs support default values let's use
import { fileInput } from "@mbostock/file-input-with-initial-value"
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more