我正在尝试从HTML头中提取特定的JSON,如下所示。
我试过结合
$(".article-body")
和
$("head")
全部运气不好-有人可以看看一下,看看什么是最好的解决方案吗?
最佳答案
您需要获取对script
元素的引用,然后访问其innerText
属性。查看以下代码段:
// get the inner text from the script element by id
let scriptElem = document.getElementById('json-data');
// or by tag name
// make sure to select the correct one from the array of elements
// to accomplish this you may check if(scriptElem.type == 'application/ld+json')
// let scriptElem = document.getElementsByTagName('script');
// parse it to a JSON
let parsedJson = JSON.parse(scriptElem.innerText);
console.log(parsedJson)
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="application/ld+json" id="json-data">
{
"some": "data"
}
</script>
</head>
<body>
<h1>JSON from script tag</h1>
</body>
</html>
关于javascript - 如何在html中提取特定json的内容?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56051592/