Skip to content

Instantly share code, notes, and snippets.

@rarous
Created October 29, 2022 12:23
Show Gist options
  • Save rarous/71ba4e89fde67b52fe25ac5145a3b9fd to your computer and use it in GitHub Desktop.
Save rarous/71ba4e89fde67b52fe25ac5145a3b9fd to your computer and use it in GitHub Desktop.
/**
* @param {Element} el
*/
function parse(el) {
const parsedJSON = JSON.parse(el.textContent);
if (Array.isArray(parsedJSON)) return parsedJSON;
return [parsedJSON];
}
/**
* @param {Document} document
* @returns {Map<string, any>}
*/
export function jsonLD(document) {
const result = new Map();
for (const script of document.querySelectorAll(
'script[type="application/ld+json"]'
)) {
try {
for (const obj of parse(script)) {
const type = obj["@type"];
if (!type) continue;
const data = result.get(type) ?? [];
data.push(obj);
result.set(type, data);
}
} catch (err) {
console.error("Error in jsonld parse", err);
}
}
return result;
}
/**
* @param {Element} el
*/
function parse(el) {
const parsedJSON = JSON.parse(el.textContent);
if (Array.isArray(parsedJSON)) return parsedJSON;
return [parsedJSON];
}
/**
* @param {Document} document
* @returns {Map<string, any>}
*/
export function jsonLD(document) {
const result = {};
for (const script of document.querySelectorAll(
'script[type="application/ld+json"]'
)) {
try {
for (const obj of parse(script)) {
const type = obj["@type"];
const data = result[type] ?? [];
data.push(obj);
result[type] = data;
}
} catch (err) {
console.error("Error in jsonld parse", err);
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment