javascript - Reading JSON from <script> Tag - Stack Overflow

How can I get JSON data embedded in a script tag?<!DOCTYPE html><html><head><scri

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 );
        </script>
    </head>
    <body>
    </body>
</html>

I'm getting:

Uncaught SyntaxError: Unexpected token u in JSON at position 0

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 );
        </script>
    </head>
    <body>
    </body>
</html>

I'm getting:

Uncaught SyntaxError: Unexpected token u in JSON at position 0

Share Improve this question asked Dec 1, 2016 at 16:34 GTS JoeGTS Joe 4,20217 gold badges62 silver badges109 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 7

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

The u es 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>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744144816a4560371.html

相关推荐

  • javascript - Reading JSON from &lt;script&gt; Tag - Stack Overflow

    How can I get JSON data embedded in a script tag?<!DOCTYPE html><html><head><scri

    8天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信