-
Notifications
You must be signed in to change notification settings - Fork 44
/
extract-json-ld.js
29 lines (26 loc) · 941 Bytes
/
extract-json-ld.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// More info on JSON-LD (Linked Data):
// https://moz.com/blog/json-ld-for-beginners
module.exports = function ($) {
const $scriptTags = $('script')
const jsonLdObjects = []
$scriptTags.each((index, el) => {
try {
if ($(el).attr('type') === 'application/ld+json') {
const parsed = JSON.parse($(el).html())
// The @graph technique in JSON-LD (Linked Data Format) syntax
// is used to create a node array. The code begins with @graph
// and then an open bracket, which opens the array and contains
// a series of nodes.
if (parsed['@graph'] && Array.isArray(parsed['@graph'])) {
parsed['@graph'].forEach(item => jsonLdObjects.push(item))
} else {
jsonLdObjects.push(parsed)
}
}
} catch (e) {
// JSON.parse() error. do nothing, skip.
// console.log(e.message)
}
})
return jsonLdObjects.filter(item => !!item)
}