Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading object from JSON file into javascript

How do I load an object into javascript if it is available in a json file?

I have the following script in my html:

<script src='scene.json'></script>
<script>
  var x = scene.x;
</script>

And this is the file scene.json, located in the same folder:

{"scene": {
  "x": 0,
  "y": 0,
  "w": 11000,
  "h": 3500,
}}

But the json file is not loaded properly (unexpected token ':') and the scene.x reference is also probably not the way it should be done. Is it possible to refer to the data directly? Or does it need to be loaded by some http request?

like image 370
Kretep Avatar asked Jul 19 '12 12:07

Kretep


3 Answers

{"scene": {
  "x": 0,
  "y": 0,
  "w": 11000,
  "h": 3500
}}

Is invalid javascript (because it's treated as a block), you probably just want a javascript file:

var scene = {
  "x": 0,
  "y": 0,
  "w": 11000,
  "h": 3500
};

If you want to keep the file as JSON, you cannot reference it from a script element and have it work while being valid JSON. You would need to use ajax request to fetch the file and parse the JSON.

like image 77
Esailija Avatar answered Sep 28 '22 23:09

Esailija


Modify this to javascript:

var scene = {
  "x": 0,
  "y": 0,
  "w": 11000,
  "h": 3500
};

Or use jQuery api and function getJSON

<script>
  var scene={};
  $.getJSON('scene.json', function(data) { 
    scene=data;
  }); 
</script>
like image 35
rogal111 Avatar answered Sep 29 '22 00:09

rogal111


set your json data to one variable like

data =  {"scene": {
  "x": 0,
  "y": 0,
  "w": 11000,
  "h": 3500
}
}

then access it as

data.scene.x //it will give 0 
like image 33
Shreedhar Avatar answered Sep 28 '22 23:09

Shreedhar