Gigalala Gigalala - 2 months ago 8
HTML Question

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'));

Answer

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.