-1

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?

1
  • If you using jQuery ajax then you can add dataType: "JSON" parameter to request. Commented Feb 18, 2014 at 8:19

2 Answers 2

1

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.
Sign up to request clarification or add additional context in comments.

Comments

0
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

1 Comment

as he didn't initialized it from his question code block, so he might just missed this as it will become undefined, as it is not defined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.