在JavaScript中从HTML源代码提取JSON [英] Extract JSON from HTML Source in JavaScript

查看:373
本文介绍了在JavaScript中从HTML源代码提取JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个简单的Greasemonkey插件,该插件应根据页面源上的值进行X操作。具体来说,在下面,我想获得'价值':

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

在这种情况下,将PEAR读取为一个变量。然后,做一些逻辑。



在JavaScript中有一种方法可以工作,因为这个值不一定是在页面上显示的。

解决方案

您需要获取脚本标记的文本内容并使用JSON.parse()将其转换为数组

var txt = document.querySelector('script [type =application / ld + json]')。textContentvar arr = JSON.parse(txt)console.log(arr [0] .value)

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


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.

解决方案

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>

这篇关于在JavaScript中从HTML源代码提取JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆