Reputation: 35
My web service is returning a JSON array called jsonString. I am using jQuery mobile. This has the value:
{
"id": "10844",
"password": "acddcd",
"role": ["PortalAdmin,ViewAllJob,SetupAdmin,Budget Approval,MarketingAdmin,ProjectManagementAdmin,HRAdmin,PayRollAdmin,SCMAdmin,VendorPortalAdmin,FinanceAdmin,AnalyticsAdmin"],
"userName": "portaluser"
}
What displaying this array in a text box (where #as
is the text box):
$('#as').val(jsonString);
When I use this code :
var a = {
"id": "10844",
"password": "acddcd",
"role": ["PortalAdmin,ViewAllJob,SetupAdmin,Budget Approval,MarketingAdmin,ProjectManagementAdmin,HRAdmin,PayRollAdmin,SCMAdmin,VendorPortalAdmin,FinanceAdmin,AnalyticsAdmin"],
"userName": "portaluser"
};
alert(a.id);
I get the right answer i.e. 10844
However, when I use this code:
var a=jsonString;
alert(a.id);
I get undefined
. Why?
Upvotes: -1
Views: 70
Reputation: 31182
In the first case you create an object, when you acces this object's id
property, there is no problem.
In the second case you give your variable a JSON as a string. That doesn't have an id
attribute, you have to parse the JSON string first, than you can acces its attributes.
Do this in the second case:
var a = JSON.parse(jsonString);
alert(a.id);
If jsonString
is not a string but an object there is two thing to mention:
jsonString
variable.jsonString
others suppose that it is a string. If it is an object then call it jsonObject
or jsonResponse
.Upvotes: 1
Reputation: 1296
var JSONstring = {
"id": "10844",
"password": "acddcd",
"role": ["PortalAdmin,ViewAllJob,SetupAdmin,Budget Approval,MarketingAdmin,ProjectManagementAdmin,HRAdmin,PayRollAdmin,SCMAdmin,VendorPortalAdmin,FinanceAdmin,AnalyticsAdmin"],
"userName": "portaluser"
};
you need to define ur JSONstring
and the rest of your code is working,
var a = JSONstring;
alert(a.id);
Upvotes: 0