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


 <!DOCTYPE html>
< html>&#xA ; < 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);
 < /脚本>
 < /头>
 <身体GT;
 < / body>
< / html>



 我收到了:

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

答案 0 :(得分:6)
<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>
&#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>