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?
{"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.
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With