仅通过javascript从网站上的json文件中提取信息



如何仅通过JavaScript从网站上的JSON文件中提取信息。 我可以使用元标记,但信息还不够。所以我必须使用 JSON。这是嵌入在网页上的 JSON 数据:

<script type="application/ld+json">
{
"@context": "https://www.schema.org",
"@type": "Product",
"name": "TF4081L02M",
"image": [
{
"url": "https://polekala.com/images/53/54/15299/main_tumb.jpg",
}
],
"description": "",
"sku": "15299",
"aggregateRating": {
"@type": "AggregateRating",
"ratingValue": 5,
"reviewCount": 40,
"bestRating": 5,
"worstRating": 0
},
},
"review": {
"@type": "Review",
"author": "",
"datePublished": "2019-12-14T00:11:02.047",
"description": ".",
"name": "Best",
"reviewRating": {
"@type": "Rating",
"bestRating": 5,
"ratingValue": 5,
"worstRating": 0
}
}
}
</script>

您在评论中说您需要帮助的具体事情是:

从 DOM 中提取 JSON

因此,您需要找到脚本元素:

const script = document.querySelector('script');

如果有多个脚本元素,并且该元素不是第一个,则可能需要更具体,因此:

const script = document.querySelector('script[type="application/ld+json"]');

如果这还不够,那么您需要根据元素出现的上下文进行调整。

然后你需要获取元素的 JSON 内容:

const json = script.textContent;

然后,您可以解析该 JSON 字符串以获取常规 JavaScript 对象。

最新更新