110

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

226

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.

8
  • 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.
    – Jonas
    Oct 31, 2011 at 16:10
  • 4
    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.
    – c-smile
    Oct 31, 2011 at 16:24
  • 12
    @WoIIe Because jQuery is used already by TS, check <script src="jquery-1.6.2.min.js"></script> there.
    – c-smile
    Apr 14, 2014 at 20:07
  • 3
    Pay attention that this is not safe, it allows XSS, codepen.io/anon/pen/xevgEM
    – felixmosh
    May 2, 2019 at 16:39
  • 1
    Note: You can't load local JSON files using the src attribute this way. textContent etc. will return an empty string. Sep 19, 2022 at 11:01
13

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
  • 47
    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.
    – George
    Oct 6, 2012 at 20:50
  • The original version of this answer was inspired by the link in the question, stackoverflow.com/questions/6713197/…
    – Jonas
    Nov 23, 2020 at 12:45
  • Should one really depend on jQuery just to do this?
    – ozanmuyes
    Jun 15 at 1:25
  • 1
    @ozanmuyes No, and that’s why I wrote code independent of jQuery.
    – Jonas
    Jun 15 at 9:44
5

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
  • 1
    The <script id="myJSON"> tag also needs the type="application/json" attribute. Jun 21, 2017 at 15:16
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
  • Thanks, it worked when I changed the json to {"org": 10, "items":["one","two"]}
    – Jonas
    Sep 28, 2011 at 9:51
  • 3
    This method is wrong. If a <script> tag has the src then it MUST NOT have any content at all. May 12, 2018 at 23:20
1

Like that will be working?

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.