RollerCosta RollerCosta - 5 months ago 30
jQuery Question

How to access JSON Object name/value?

function (data) {
//add values based on activity type
//data = JSON.parse(data);
//alert(abc.Phone1);

alert(data.myName)

alert(data.toString());
if (activityType == "Phone") {
}
return;

},


As you can see this callback function of
$.ajax
taking
JSON
data from controller.

For example:

[{"name":"myName" ,"address": "myAddress" }]


In this case my first alert giving me undefined and second/third alert popup comes up with:

[{"name":"myName" ,"address": "myAddress" }]


How can I access value by name so that my first alert filled out with
myName
which is value of
name
?

Answer

In stead of parsing JSON you can do like followng:

$.ajax({
  ..
  dataType: 'json' // using json, jquery will make parse for  you
});

To access a property of your JSON do following:

data[0].name;

data[0].address;

Why you need data[0] because data is an array, so to its content retrieve you need data[0] (first element), which gives you an object {"name":"myName" ,"address": "myAddress" }.

And to access property of an object rule is:

Object.property

or sometimes

Object["property"] // in some case

So you need

data[0].name and so on to get what you want.


If you not

set dataType: json then you need to parse them using $.parseJSON() and to retrieve data like above.