如何从 JavaScript 中读取 script-tag 中的 JSON?

我有一个动态生成的页面,我想在其中使用静态 JavaScript 并将 JSON 字符串作为参数传递给它。我见过 Google 使用这种方法(参见 Google 的 + 1按钮: 他们是怎么做到的?)。

但是我应该如何从 JavaScript 中读取 JSON 字符串呢?

<html>
<head>
<script src="jquery-1.6.2.min.js"></script>
<script src="myscript.js">{"org": 10, "items":["one","two"]}</script>
</head>
<body>
Hello
</body>
</html>

在这个 JavaScript 中,我想使用 HTML 文档中的 JSON 参数 {"org": 10, "items":["one","two"]}。我不知道使用 jQuery 或不使用 jQuery 是否最好。

$(function() {
// read JSON


alert("the json is:")
})
119808 次浏览
JSON.parse($('script[src="mysript.js"]').html());

or invent some other method to identify the script.

Maybe instead of .html() you might need .text(). Not sure. Try them both.

I ended up with this JavaScript code to be independent of jQuery.

var jsonElement = document.getElementById('json-script-tag');
var myObject = JSON.parse(jsonElement.textContent);

I would change the script declaration to this:

<script id="data" type="application/json">{"org": 10, "items":["one","two"]}</script>

Note type and id fields. After that

var data = JSON.parse(document.getElementById('data').textContent);

will work just fine in all browsers.

The type="application/json" is needed to prevent browser from parsing it while loading.

And the reason why we use textContent instead of innerHTML or innerText to read the raw Json text is because innerHTML tries to parse the contents as HTML which will lead to slower performance and possible parsing bugs and XSS attacks, and innerText won't grab the raw text and will instead look for human-visible text, whereas textContent grabs the pure text as-is (which is what you want). See https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent for more details about why innerHTML and innerText are bad.

To read JSON in <script id="myJSON"> use

var manifest= document.getElementById('myJSON').innerHTML; //sets manifest to the text in #myJSON
manifest= JSON.parse(manifest) //Converts text into JSON

You can also use methods to point to the script like document.scripts[0]

    //var manifest= JSON.parse(document.getElementById('myJSON').innerHTML); /*Shortend of 2&3*/
var manifest= document.getElementById('myJSON').innerHTML; //Gets text in #myJSON
manifest= JSON.parse(manifest) //Converts it into JSON
document.getElementById('test').innerHTML= manifest.name+ '<br/>'+ manifest.otherOptions; //Displays it
console.log('manifest')
console.log(manifest);
<head>
<script type="application/json" id="myJSON">
{"name":"Web Starter Kit", "otherOptions":"directly here"}
</script>
</head>
<body>
<p id="test"></p>
</body>