Jonas Jonas - 1 month ago 4x
Javascript Question

How can I read a JSON in the script-tag from JavaScript?

I have a dynamically generated page where I want to use a static JavaScript and pass it a JSON string as a parameter. I have seen this approach used by Google (see Google's +1 Button: How do they do it?).

But how should I read the JSON string from the JavaScript?

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

In this JavaScript I would like to use the JSON argument
{"org": 10, "items":["one","two"]}
from the HTML document. I don't know if it's best to do it with jQuery or without.

$(function() {
// read JSON

alert("the json is:")


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($("#data").html());

will work just fine in all browsers.

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