78
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?

Daniel
  • 3,115
  • 5
  • 28
  • 39
RollerCosta
  • 5,020
  • 9
  • 53
  • 71

8 Answers8

115

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.

Community
  • 1
  • 1
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
  • http://maps.googleapis.com/maps/api/geocode/json?latlng=20,77&sensor=false from this url how should get "formatted_address" field value in a variable? success : function(data) { address = data['formatted_address'];} throws an error – user3816325 Apr 14 '16 at 09:50
  • is there a more optimized way to do so? if I have a json list of more than 20 names and i need to display their value, but I don't know if which one of them will be returned in the json, it could be ony one or 3 or 10 or all 20 of them, should I repeat the same for each one of them, for example: `if data[0].name : console.log(data[0].name); if data[0].adress : console.log(data[0].adress); ..` – Armance Nov 30 '16 at 10:09
  • could `data[0].[0]` work, to access `name`? Looking at it like an array. – Malcolm Salvador Mar 08 '17 at 00:15
32

The JSON you are receiving is in string. You have to convert it into JSON object You have commented the most important line of code

data = JSON.parse(data);

Or if you are using jQuery

data = $.parseJSON(data)
U.P
  • 7,357
  • 7
  • 39
  • 61
  • even on uncommenting the line i receive undefined – RollerCosta Jun 05 '12 at 10:14
  • That is because your JSON is an array. Try data[0].name instead of data.name. And make sure you access property not value i.e. data[0].name (property) instead of what you are doing in your question data.myName(which is value) – U.P Jun 05 '12 at 10:18
16

If you response is like {'customer':{'first_name':'John','last_name':'Cena'}}

var d = JSON.parse(response);
alert(d.customer.first_name); // contains "John"

Thanks,

Mahendran Sakkarai
  • 8,381
  • 6
  • 44
  • 66
  • Hi, If I wanted to extract 'customer' how would I do that where customer is the actual thing I want. In my case I want to extract aboutme.jpg that below as a string b'{"_id":"2","_rev":"5-760e627e77645e960c5cc40ea6cf03a2","_attachments":{"aboutme.jpg":{"content_type":"image/jpeg","revpos":3,"digest":"md5-mG5uU4IRGuY/f9PbZ8AIbQ==","length":98831,"stub":true}}}\n' – Andrew Irwin Nov 26 '16 at 22:11
7

You should do

alert(data[0].name); //Take the property name of the first array

and not

 alert(data.myName)

jQuery should be able to sniff the dataType for you even if you don't set it so no need for JSON.parse.

fiddle here

http://jsfiddle.net/H2yN6/

Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
4

Try this code..

function (data) {


var json = jQuery.parseJSON(data);
alert( json.name );


}
Kabilan S
  • 1,104
  • 4
  • 15
  • 31
  • i tried it before and getting an error Microsoft JScript runtime error: Object doesn't support property or method 'parseJSON' – RollerCosta Jun 05 '12 at 10:11
3

You might want to try this approach:

var  str ="{ "name" : "user"}";
var jsonData = JSON.parse(str);     
console.log(jsonData.name)
//Array Object
str ="[{ "name" : "user"},{ "name" : "user2"}]";
jsonData = JSON.parse(str);     
console.log(jsonData[0].name)
baduker
  • 19,152
  • 9
  • 33
  • 56
2

I think you should mention dataType: 'json' in ajax config and to access that value:

data[0].name
The System Restart
  • 2,873
  • 19
  • 28
0

Here is a friendly piece of advice. Use something like Chrome Developer Tools or Firebug for Firefox to inspect your Ajax calls and results.

You may also want to invest some time in understanding a helper library like Underscore, which complements jQuery and gives you 60+ useful functions for manipulating data objects with JavaScript.

Butifarra
  • 1,094
  • 8
  • 12