user7518095 user7518095 - 4 years ago 102
Ajax Question

AJAX - Extracting Info from JSON Object

I have data in a JSON object with the following format:

[{"Feature 1 Name":111,"Feature 2":111,"Feature 3":"stringforfeature3"}]


I've started to write some code to pull information from an API, but am not sure how to extract information (for instance, "stringforfeature3" if I somehow call "Feature 3") from the JSON object.

ajax: {
type: "GET",
url: '/api/apiname/info/moreinfo', //where i'm pulling info from
dataType: "JSON",
success: function(data, textStatus, jqXHR) {
return {
title: // Where I'd like to use the extracted information
};
}
},


Any advice would be greatly appreciated!

Answer Source

You should be able to extract the data using square bracket notation:

success: function(data, textStatus, jqXHR) {
    return {
        title: data[0]['Feature 3']
      };
    }

You result is an array, so I used data[0] to get the first item of array, or {"Feature 1 Name":111,"Feature 2":111,"Feature 3":"stringforfeature3"}.

In JavaScript you can access the same variable either using object.variable or object['variable']. Since your variable name has spaces, you are left with second option - data[0]['Feature 3']. Your result will be stringforfeature3.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download