oshirowanen
oshirowanen

Reputation: 15925

Checking the value of json data

If I have json data which looks like this:

{"d":1}

How do I check if that 1 is a 1 or a 0?

I have tried the following, but it goes straight to the else, even when I can see that the json data has a 1.

success: function(data) {

    if (data[0]) {
        console.log("Results...");
    } else {
        console.log("No results...");
    }

the data contains {"d":1}

Upvotes: 0

Views: 93

Answers (6)

Sonu Sindhu
Sonu Sindhu

Reputation: 1792

Try this

if (data.d == 1){
   // do
}

Upvotes: 0

Matthijs
Matthijs

Reputation: 568

You can do:

data.d == 1

Example: http://jsfiddle.net/avVRs/

Upvotes: 0

bblincoe
bblincoe

Reputation: 2483

You must use the "d" key to access the data associated with it, which is 1.

JSON is simply key-value pairs.

e.g.

if (data.d == 1) {
...
}

Upvotes: 0

UweB
UweB

Reputation: 4110

You'd be right if the JSON was actually an array:

[{"d":1}]

Since it's not, you can simply

if (data) {
    // Do stuff
}

Upvotes: 0

Ferdinand Torggler
Ferdinand Torggler

Reputation: 1422

data is a hash, so this should work:

if (data.d == 1) {...}

Upvotes: 1

  if (data["d"] == 1)

or simply

  if (data.d == 1)

Upvotes: 4

Related Questions