GTS Joe
GTS Joe

Reputation: 4152

Reading JSON from <script> Tag

How can I get JSON data embedded in a script tag?

<!DOCTYPE html>
<html>
    <head>
        <script id="data" type="application/json">{org: 10, items:['one','two']}</script>
        <script type="text/javascript">
            var obj = JSON.parse( document.getElementById('data').value );
            console.log( obj );
            console.log( obj.org );
        </script>
    </head>
    <body>
    </body>
</html>

I'm getting:

Uncaught SyntaxError: Unexpected token u in JSON at position 0

Upvotes: 1

Views: 6871

Answers (2)

Quentin
Quentin

Reputation: 943556

<script> elements are not form controls. They don't have value properties (so. when you read it, you get undefined which is "undefined" when cast to a string, and that isn't valid JSON).

Read the content of the text node inside the element instead.

You also need to write JSON instead of a JavaScript object literal.

  • Property names must be strings, not identifiers.
  • Strings must be quoted with " not '.

<script id="data" type="application/json">{"org": 10, "items":["one","two"]}</script>
<script type="text/javascript">
var obj = JSON.parse(document.getElementById('data').firstChild.data);
  console.log(obj);
  console.log(obj.org);
</script>

Upvotes: 7

jehna1
jehna1

Reputation: 3130

The u comes from "undefined". Try:

JSON.parse( document.getElementById('data').innerHTML );

...but keep in mind that your current input is not JSON. So correctly formatted it would be:

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

Upvotes: 0

Related Questions