Public
Edited
Oct 10, 2023
Insert cell
Insert cell
newParse = {
function convertString(value) {
// Attempt to convert to number
const numValue = parseFloat(value);
if (!isNaN(numValue)) {
return numValue;
}
// Attempt to convert to boolean
if (value.toLowerCase() === "true") {
return true;
} else if (value.toLowerCase() === "false") {
return false;
}
// Default to string
return value;
}

function xmlToJson(xmlNode) {
if (xmlNode.nodeType === 3) {
// If the node is a text node
return convertString(xmlNode.nodeValue.trim());
}

// If the node has no attributes and no children, return an empty string
if (
xmlNode.childNodes.length === 0 &&
(!xmlNode.attributes || xmlNode.attributes.length === 0)
) {
return "";
}

let jsonObj = {};

if (xmlNode.attributes && xmlNode.attributes.length > 0) {
let attrsObj = {};
for (let i = 0; i < xmlNode.attributes.length; i++) {
const attr = xmlNode.attributes[i];
attrsObj[attr.name] = convertString(attr.value);
}
jsonObj["attr"] = attrsObj;
}

for (let i = 0; i < xmlNode.childNodes.length; i++) {
const childNode = xmlNode.childNodes[i];
const childJson = xmlToJson(childNode);

if (childJson !== undefined && childJson !== "") {
if (childNode.nodeName === "#text" && xmlNode.childNodes.length === 1) {
return childJson;
}

if (jsonObj[childNode.nodeName]) {
if (!Array.isArray(jsonObj[childNode.nodeName])) {
jsonObj[childNode.nodeName] = [jsonObj[childNode.nodeName]];
}
jsonObj[childNode.nodeName].push(childJson);
} else {
jsonObj[childNode.nodeName] = childJson;
}
}
}

return jsonObj;
}

function parse(xmlStr) {
const parser = new DOMParser();
const doc = parser.parseFromString(xmlStr, "application/xml");
return { OME: xmlToJson(doc.documentElement) };
}

return parse;
}
Insert cell
Insert cell
Insert cell
// new impl
newParserResult = fromString(sampleOMEXML, newParse)
Insert cell
// fast-xml-parser
oldParserResult = {
const parser = await import("https://esm.sh/fast-xml-parser@3");
return fromString(sampleOMEXML, (str) =>
parser.parse(str, {
attributeNamePrefix: "",
attrNodeName: "attr",
parseNodeValue: true,
parseAttributeValue: true,
ignoreAttributes: false
})
);
}
Insert cell
Insert cell
// No differences between the two objects; should test with more examples.
// Need to call ".format()" because it's a function and not diffable
diffResult = {
const { diff } = await import("https:esm.sh/deep-object-diff");
return diff(
newParserResult.map((img) => ({ ...img, format: img.format() })),
oldParserResult.map((img) => ({ ...img, format: img.format() }))
);
}
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