[英]How do I extract the contents of a specific json within the html?
您需要获取对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>
尝试这个:
// [0] get the first script tag with type 'application/ld+json'
JSON.parse($("script[type='application/ld+json']")[0].textContent)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.