问题
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