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

时间:2019-05-09 03:00:18

标签: javascript html

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

我尝试过

的组合
$(".article-body")

$("head")

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

HTML

2 个答案:

答案 0 :(得分:2)

您需要获取对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>

答案 1 :(得分:0)

尝试一下:

// [0] get the first script tag with type 'application/ld+json'
JSON.parse($("script[type='application/ld+json']")[0].textContent)