Skip to content

Instantly share code, notes, and snippets.

@ngopal
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ngopal/c4070a87e86bb430bb31 to your computer and use it in GitHub Desktop.
Save ngopal/c4070a87e86bb430bb31 to your computer and use it in GitHub Desktop.
A list of different ways to parse json in javascript. Currently unfinished
// To parse CSV, TSV, etc
// https://code.google.com/p/jquery-csv/ --> Library to parse CSV
// otherwise use ajax call with dataType set to text
// If the JSON file is in string form
// http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript
var json = '{"result":true,"count":1}';
var obj = JSON.parse(json);
console.log(obj.count);
// If using JQuery, and file is from an external domain
$.getJSON(url, function (json) {
alert(json.result);
$.each(json.list, function (i, fb) {
alert(fb.result);
});
});
// If using Ajax
// set dataType to 'json' for json data, 'jsonp' for cross-domain API call
$.ajax({
type: 'GET',
url: "myfile.csv",
dataType: "text",
success: function (result) {
console.log(result);
},
});
// If using XHR and AJAX (and this can get quite verbose...)
// https://mathiasbynens.be/notes/xhr-responsetype-json
var getJSON = function(url, successHandler, errorHandler) {
var xhr = typeof XMLHttpRequest != 'undefined'
? new XMLHttpRequest()
: new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onreadystatechange = function() {
var status;
var data;
// http://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
if (xhr.readyState == 4) { // `DONE`
status = xhr.status;
if (status == 200) {
successHandler && successHandler(xhr.response);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
getJSON('https://mathiasbynens.be/demo/ip', function(data) {
alert('Your public IP address is: ' + data.ip);
}, function(status) {
alert('Something went wrong.');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment