MikePolinske MikePolinske - 6 months ago 14
JSON Question

How do I parse a JSON object in JavaScript

I have the following function, which currently just displays the object returned from the GET request to the console. What I need to do is parse the "data" object so that I can return the "output" string from data to my web page. Any help would be greatly appreciated.

window.onload = function() {
var output = $.ajax({
url: 'https://ajith-holy-bible.p.mashape.com/GetVerseOfaChapter?Book=John&chapter=3&Verse=16', // The URL to the API. You can get this by clicking on "Show CURL example" from an API profile
type: 'GET', // The HTTP Method, can be GET POST PUT DELETE etc
data: {}, // Additional parameters here
dataType: 'json',
success: function (data) {
//
//Change data.source to data.something , where something is whichever part of the object you want returned.
//To see the whole object you can output it to your browser console using:
console.log(data);
},
error: function (err) {
alert(err);
},
beforeSend: function (xhr) {
xhr.setRequestHeader("X-Mashape-Authorization", "my_key_here"); // Enter here your Mashape key
}
});
}

Answer

I'm not sure how your JSON looks like but let's say is

{
    "foo": "some value",
    "bar": "some other value"
}

then you could do:

success: function (data) {

    console.log(data);

    var dataObj = $.parseJSON(data);

    $.each(dataObj, function(key, value) {
        if(key == "foo") {
            // do something with foo's value
            console.log(value);         
        }
        if(key == "bar") {
            // do something with bar's value
            console.log(value); 
        }
    });

}