user3322378
user3322378

Reputation: 35

Json string not able to display using jquery

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

Answers (2)

totymedli
totymedli

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:

  1. As rockStar said be sure that your variable exists and you assigned the result from your web service to your jsonString variable.
  2. This is bad naming. If you call it jsonString others suppose that it is a string. If it is an object then call it jsonObject or jsonResponse.

Upvotes: 1

rockStar
rockStar

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);

fiddle

Upvotes: 0

Related Questions