udhaya
udhaya

Reputation: 1

How do I convert a JSON string to a JS object and check the value of a property?

I have the following JSON-encoded object in a string:

{
  "loggedin": 0,
  "error_message": "login_failed",
  "success_message": "",
  "username": "",
  "sessionId": ""
}

How do I convert this to an object in JS, then check that its loggedin property is 0 or 1?

Upvotes: 0

Views: 554

Answers (3)

udhaya
udhaya

Reputation: 1

ha ha got it, should use like this var obj = $.evalJSON(responseText); alert(obj.error_message); //output:login_failed

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816482

Do you mean:

var json = {"loggedin":0,"error_message":"login_failed","success_message":"","username":"","sessionId":""}

if(json.loggedin == 0) {
   // do something
}
else {
   // do something else
}

Update:

If you have the JSON as string, you have to parse it before you can do this. So maybe you have to do this:

var responseText = JSON.parse(responseText);

Upvotes: 2

Naeem Sarfraz
Naeem Sarfraz

Reputation: 7430

var myJSONObject = {"loggedin":0,"error_message":"login_failed","success_message":"","username":"","sessionId":""};
if (myJSONObject.loggedin === 0) {
   // do something
} else {
   // do something else
}

Upvotes: 0

Related Questions