Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a JSON file in javascript

Tags:

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.

like image 901
Stephan Avatar asked Jan 28 '11 12:01

Stephan


People also ask

Can you use JSON in JavaScript?

JSON is a text-based data format following JavaScript object syntax, which was popularized by Douglas Crockford. Even though it closely resembles JavaScript object literal syntax, it can be used independently from JavaScript, and many programming environments feature the ability to read (parse) and generate JSON.

What does JSON () do in JavaScript?

json() The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON .


1 Answers

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  }); 
like image 199
Raynos Avatar answered Oct 13 '22 12:10

Raynos