简体   繁体   English

如何在javascript中使用JSON文件

[英]How to use a JSON file in javascript

First off, I am a newcomer to the Javascript realm. 首先,我是Javascript领域的新手。 I have a JSON file, such as the following: 我有一个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. 我一直在做很多关于如何将这个文件带回我的脚本的研究,只是为了找到将字符串编码成JSON文件的方法。 Basically, I want to read this file through javascript, something like this... (I know this isn't how you code) 基本上,我想通过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术语相提并论。

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. 您打算如何获得它以及您使用的服务器代码。

Once you have you can use JSON.parse(string) on it. 一旦你有了,你可以使用JSON.parse(string) You can include the json2.js file if you need to support older browsers. 如果需要支持旧版浏览器,可以包含json2.js文件。

If you use jQuery you can also try jQuery.parseJSON for 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 JSONP or some kind of library with ajax functionality like jQuery.ajax or Ajax.Request . 要加载它,您可以使用JSONP或某种具有Ajax功能的库,如jQuery.ajaxAjax.Request It can be done in raw javascript but that's just ugly and re-inventing the wheel. 它可以在原始的javascript中完成,但这只是丑陋并重新发明轮子。

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

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM