将对象从 JSON 文件加载到 javascript 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11561000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:19:43  来源:igfitidea点击:

Loading object from JSON file into javascript

javascriptjson

提问by Kretep

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

如果对象在 json 文件中可用,如何将对象加载到 javascript 中?

I have the following script in my html:

我的 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.json,位于同一文件夹中:

{"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?

但是 json 文件没有正确加载(意外的标记 ':')并且 scene.x 引用也可能不是它应该完成的方式。可以直接引用数据吗?还是需要通过一些http请求加载?

采纳答案by Esailija

{"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:

是无效的 javascript(因为它被视为一个块),你可能只想要一个 javascript 文件:

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.

如果要将文件保留为 JSON,则不能从脚本元素引用它并使其在有效 JSON 的情况下工作。您需要使用 ajax 请求来获取文件并解析 JSON。

回答by rogal111

Modify this to javascript:

将此修改为javascript:

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

Or use jQuery api and function getJSON

或者使用 jQuery api 和函数getJSON

<script>
  var scene={};
  $.getJSON('scene.json', function(data) { 
    scene=data;
  }); 
</script>

回答by Shreedhar

set your json data to one variable like

将您的 json 数据设置为一个变量,例如

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

then access it as

然后访问它

data.scene.x //it will give 0