125

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?

<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>

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:")
})

5 Answers 5

257

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Well, I want the script-tag point to a JavaScript, so it's not only for JSON. The JSON is only an argument to the script.
According to HTML5 spec: dev.w3.org/html5/markup/script.html the <script> element that has defined SRC shall not contain anything other than new lines and/or comments. See "A script element with a src attribute must contain only:" in the link above. Otherwise HTML validator's will complain.
@WoIIe Because jQuery is used already by TS, check <script src="jquery-1.6.2.min.js"></script> there.
Pay attention that this is not safe, it allows XSS, codepen.io/anon/pen/xevgEM
Note: You can't load local JSON files using the src attribute this way. textContent etc. will return an empty string.
|
12

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);

4 Comments

Why not just give the script an ID and grab it with document.getElementById? That way, you don't have to remember to keep it last. Nor will whoever else changes the page in the future.
The original version of this answer was inspired by the link in the question, stackoverflow.com/questions/6713197/…
Should one really depend on jQuery just to do this?
@ozanmuyes No, and that’s why I wrote code independent of jQuery.
6

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>

1 Comment

The <script id="myJSON"> tag also needs the type="application/json" attribute.
3
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.

2 Comments

Thanks, it worked when I changed the json to {"org": 10, "items":["one","two"]}
This method is wrong. If a <script> tag has the src then it MUST NOT have any content at all.
2

Like that will be working?

<script id="data" type="application/json" src="https://mycstripc.co">
var data = JSON.parse(document.getElementById('data').textContent);
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.