How can I read a JSON in the script-tag from JavaScript?

女生的网名这么多〃 提交于 2019-11-27 03:31:10
c-smile

I would change the script declaration to this:

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

Note type and id fields. After that

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

will work just fine in all browsers.

The type="application/json" is needed to prevent browser from parsing it while loading.

I ended up with this JavaScript code to be independent of jQuery.

var json = document.getElementsByTagName('script');
var myObject = JSON.parse(json[json.length-1].textContent);

To read JSON in <script id="myJSON"> use

var manifest= document.getElementById('myJSON').innerHTML; //sets manifest to the text in #myJSON
manifest= JSON.parse(manifest) //Converts text into JSON

You can also use methods to point to the script like document.scripts[0]

    //var manifest= JSON.parse(document.getElementById('myJSON').innerHTML); /*Shortend of 2&3*/
var manifest= document.getElementById('myJSON').innerHTML; //Gets text in #myJSON
manifest= JSON.parse(manifest) //Converts it into JSON
document.getElementById('test').innerHTML= manifest.name+ '<br/>'+ manifest.otherOptions; //Displays it
console.log('manifest')
console.log(manifest);
<head>
<script type="application/json" id="myJSON">
  {"name":"Web Starter Kit", "otherOptions":"directly here"}
</script>
</head>
<body>
<p id="test"></p>
</body>
JSON.parse($('script[src="mysript.js"]').html());

or invent some other method to identify the script.

Maybe instead of .html() you might need .text(). Not sure. Try them both.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!