Gigalala Gigalala - 10 months ago 35
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 type="text/javascript">
$(function() {
var x = JSON.parse($('#myJson').html());
alert(; //Foo

my code:

<script src="Game.js"></script>
<script type="application/json" id="data">

Javascript code:

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

Answer Source

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 '.


<script type="application/json" id="data">
<script src="Game.js"></script>

Would work, provided you have something like


in Game.js.