从<script>标签中读取JSON

时间:2016-12-01 16:34:50

标签: javascript json object

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

&#xA;&#xA;
 &lt;!DOCTYPE html&gt;&#xA;&lt; html&gt;&#xA ; &LT; HEAD&GT;&#XA; &lt; script id =“data”type =“application / json”&gt; {org:10,items:['one','two']}&lt; / script&gt;&#xA; &lt; script type =“text / javascript”&gt;&#xA; var obj = JSON.parse(document.getElementById('data')。value);&#xA; console.log(obj);&#xA; console.log(obj.org);&#xA; &LT; /脚本&GT;&#XA; &LT; /头&GT;&#XA; &LT;身体GT;&#XA; &lt; / body&gt;&#xA;&lt; / html&gt;&#xA;  
&#xA;&#xA;

我收到了:

&#xA; &#xA;

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

&#xA;

2 个答案:

答案 0 :(得分:6)

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

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

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

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

&#13;
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

u来自&#34; undefined&#34;。尝试:

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

...但请记住,您当前的输入不是JSON。如此正确的格式化将是:

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