Extract JSON from HTML Source in JavaScript

送分小仙女□ 提交于 2019-12-24 08:39:46

问题


I am in the process of building a simple Greasemonkey plugin that should do X action depending on a 'value' on the source of a page. Specifically, in the below, I would like to get at the 'value':

<script type="application/ld+json">
[
    {
      "value": "PEAR"
    }
]
</script>

In this case, reading PEAR to a variable. Thereafter, doing some logic.

Is there an approach in Javascript that would work as this value isnt necessarily 'shown' on the page.


回答1:


You would need to get the text content of the script tag and convert it to array using JSON.parse()

var txt = document.querySelector('script[type="application/ld+json"]').textContent
var arr = JSON.parse(txt)
console.log(arr[0].value)
<script type="application/ld+json">
[
    {
      "value": "PEAR"
    }
]
</script>


来源:https://stackoverflow.com/questions/50351217/extract-json-from-html-source-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!