繁体   English   中英

如何在html中提取特定json的内容?

[英]How do I extract the contents of a specific json within the html?

我正在尝试从HTML头中提取特定的JSON,如下所示。

我试过结合

$(".article-body")

$("head")

全部运气不好-有人可以看看一下,看看什么是最好的解决方案吗?

的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM