Created
October 29, 2022 12:23
-
-
Save rarous/71ba4e89fde67b52fe25ac5145a3b9fd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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