答案 0 :(得分:2)
您需要获取对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>
答案 1 :(得分:0)
尝试一下:
// [0] get the first script tag with type 'application/ld+json'
JSON.parse($("script[type='application/ld+json']")[0].textContent)