【发布时间】:2021-01-31 17:05:48
【问题描述】:
我一直在尝试找到一种方法来获取应用程序/ld+json 内容并将其保存到本地对象。我想要的是将它保存到一个对象中,并且在我的程序中,我将能够 console.log(data.offers.availability) 这将导致日志记录:“InStock”,以及每个数据值。
我目前有这个:
let content = JSON.stringify($("script[type='application/ld+json']").html())
let filteredJson = content.replace(/\\n/g, '')
let results = JSON.parse(filteredJson)
console.log(results)
这会导致:- 不允许我使用 console.log(results.offers.availability)
{ "@context": "http://schema.org/",
"@type": "Product", "name": "Apex Legends - Bangalore - Mini Epics",
"description": "<div class="textblock"><p><h2>Apex Legends - Bangalore - Mini Epics </h2><p>Helden uit alle uithoeken van de wereld strijden voor eer, roem en fortuin in Apex Legends. Weta Workshop betreedt the Wild Frontier en brengt Bangalore met zich mee - Mini Epics style!</p><p>Verzamel alle Apex Legends Mini Epics en voeg ook Bloodhound en Mirage toe aan je collectie!</p></p></div>",
"brand": {
"@type": "Thing",
"name": "Game Mania"
},
"aggregateRating": {
"@type": "AggregateRating",
"ratingValue": "5",
"ratingCount": "2"
},
"offers": {
"@type": "Offer",
"priceCurrency": "EUR",
"price": "19.98",
"availability" : "InStock"
}
}
【问题讨论】:
-
呃,不要用
JSON.stringify?此外,我会推荐.text()而不是.html()以获得没有转义的实体。 -
@Bergi:有趣的是,当我将
.text()与我的示例代码一起使用时,我得到了SyntaxError: Unexpected end of JSON input,它与.html()一起使用,或者我这样做的方式。.text()似乎返回一个空字符串。 -
@eol 您在节点中使用什么 DOM 实现,
$是什么?我记得一些浏览器没有脚本的文本内容的问题。但不管怎样,.html()和.text()都返回字符串,而JSON.stringify()是错误的。要删除换行符,请替换/\n/g而不是/\\n/g。 -
我正在使用cheerio。经过一些调试,我发现了以下行:github.com/cheeriojs/cheerio/blob/main/lib/static.js#L102。据此,如果当前元素的 tagName 为
script,则它们不会下降/递归,因此将返回一个空字符串。
标签: javascript node.js json ld