简体   繁体   中英

How to read and parse json file from html tag

I have some html file with a script tag of type `application/json', i am trying to read that json on my javascript code which is on separate file and loaded to that html. But i can only find jQuery examples, and i want to do it in pure javascript.

Here is an example on jquery:

<script id="myJson" type="application/json">
 { 
   name: 'Foo' 
 }
</script>

<script type="text/javascript">
    $(function() {
        var x = JSON.parse($('#myJson').html());
        alert(x.name); //Foo
     });
</script>

my code:

<script src="Game.js"></script>
<script type="application/json" id="data">
{'name':'foo'}
</script>

Javascript code:

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

Your script doesn't find the json as the json isn't there when the js script runs, put the json tag before the javascript script tag. Also, what you have there as json isn't (valid) json. json has " , not ' .

So

<script type="application/json" id="data">
    {"name":"foo"}
</script>
<script src="Game.js"></script>

Would work, provided you have something like

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

in Game.js .

If you want to embed JSON in an html element, you can use Element.dataset

 window.onload = function() { console.log(JSON.parse(document.getElementById("myJson").dataset.json)) } 
 <script id="myJson" type="text/plain" data-json='{"name":"Foo"}'></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM