如何在 javascript 中使用 JSON 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4828207/
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-23 14:18:24  来源:igfitidea点击:

How to use a JSON file in javascript

javascriptjson

提问by Stephan

First off, I am a newcomer to the Javascript realm. I have a JSON file, such as the following:

首先,我是 Javascript 领域的新手。我有一个 JSON 文件,如下所示:

{"markers": [
  {
   "abbreviation": "SPA",
   "latitude":-13.32,
   "longitude":-89.99,
   "markerImage": "flags/us.png",
   "information": "South Pole",
  },

.... lots more of these in between ....

{
   "abbreviation": "ALE",
   "latitude":-62.5,
   "longitude":82.5,
   "markerImage": "flags/us.png",
   "information": "Alert",
  },
] }

I have been doing a lot of research as to how I can bring this file back into my script only to find ways to encode strings into JSON files. Basically, I want to read this file through javascript, something like this... (I know this isn't how you code)

我一直在研究如何将这个文件带回我的脚本,只是为了找到将字符串编码为 JSON 文件的方法。基本上,我想通过javascript读取这个文件,就像这样......(我知道这不是你编码的方式)

object data = filename.json  
document.write(data.markers.abbreviation[1])

Can someone please give me clear instruction on how to go about doing this. Remember, I am a newcomer and need specifics since I'm not up to par with the javascript jargon.

有人可以给我明确的指示如何去做这件事。请记住,我是新手,需要详细说明,因为我不符合 javascript 行话。

回答by Raynos

First you need a handle on a file. You need to get it somehow either through ajax or through server-side behaviour.

首先你需要一个文件的句柄。您需要通过 ajax 或服务器端行为以某种方式获取它。

You need to tell use where the file is. How you plan to get it and what serverside code your using.

您需要告诉 use 文件在哪里。您计划如何获取它以及您使用的服务器端代码。

Once you have you can use JSON.parse(string)on it. You can include the json2.jsfile if you need to support older browsers.

有了之后就可以使用JSON.parse(string)了。如果您需要支持旧浏览器,您可以包含json2.js文件。

If you use jQuery you can also try jQuery.parseJSONfor parsing instead.

如果您使用 jQuery,您也可以尝试jQuery.parseJSON进行解析。

An option for remotely getting json would be using jQuery.getJSON

远程获取 json 的一个选项是使用 jQuery.getJSON

To load it you can either use JSONPor some kind of library with ajax functionality like jQuery.ajaxor Ajax.Request. It can be done in raw javascript but that's just ugly and re-inventing the wheel.

要加载它,您可以使用JSONP或某种具有 ajax 功能的库,例如jQuery.ajaxAjax.Request。它可以在原始 javascript 中完成,但这只是丑陋和重新发明轮子。

$.getJSON("document.json", function(data) {
    console.log(data);
    // data is a JavaScript object now. Handle it as such

});