Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 806
RollerCosta Avatar asked Jun 05 '12 10:06

RollerCosta


People also ask

How can we access values from JSON object?

To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.

How do I get the name of a JSON object?

You simply use a dot like so: obj.StudentData.Name . This is of course assuming as Kevin B says below, that you've used JSON. parse and that it's valid json (the stuff you posted is not valid json - you're missing starting brackets and DateOfBirth isn't a string).

Do JSON objects have names?

JSON names are on the left side of the colon. They need to be wrapped in double quotation marks, as in “name” and can be any valid string. Within each object, keys need to be unique. JSON values are found to the right of the colon.


2 Answers

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.

like image 126
thecodeparadox Avatar answered Oct 10 '22 01:10

thecodeparadox


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) 
like image 32
U.P Avatar answered Oct 10 '22 01:10

U.P