简体   繁体   中英

How to use a JSON file in javascript

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

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

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.

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

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. You can include the json2.js file if you need to support older browsers.

If you use jQuery you can also try jQuery.parseJSON for parsing instead.

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

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

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

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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