简体   繁体   English

从JavaScript中的HTML源提取JSON

[英]Extract JSON from HTML Source in JavaScript

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. 我正在构建一个简单的Greasemonkey插件,该插件应根据页面源上的“值”执行X操作。 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. 在这种情况下,将PEAR读取为变量。 Thereafter, doing some logic. 此后,做一些逻辑。

Is there an approach in Javascript that would work as this value isnt necessarily 'shown' on the page. Javascript中是否有一种方法可以工作,因为此值不一定在页面上“显示”。

You would need to get the text content of the script tag and convert it to array using JSON.parse() 您将需要获取脚本标签的文本内容,然后使用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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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