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.
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.
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 .
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With