从<script>标签中读取JSON

GTS*_*Joe 1 javascript json object

如何将JSON数据嵌入脚本标记中?

<!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>
Run Code Online (Sandbox Code Playgroud)

我越来越:

未捕获的SyntaxError:位于0的JSON中的意外标记u

Que*_*tin 7

<script>元素不是表单控件.它们没有value属性(所以.当你读它时,你得到的undefined"undefined"当转换为字符串时,这是无效的JSON).

请改为读取元素内文本节点的内容.

您还需要编写JSON而不是JavaScript对象文字.

  • 属性名称必须是字符串,而不是标识符.
  • 字符串必须用引号引起来"'.

<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>
Run Code Online (Sandbox Code Playgroud)