0

I have a json output as

amt: "10.00"
email: "sam@gmail.com"
merchant_id: "sam"
mobileNo: "9874563210"
orderID: "123456"
passkey: "1234"

Literally Im trying to do this in javascript

if(the json output has the key merchant_id)
{
//do something
}

How is it possible to find if a json output has a key like as I demonstrated above?Is it possible,Or is there any alternate method for it?

Ajeesh
  • 5,650
  • 8
  • 30
  • 52
  • possible duplicate of [Checking if an associative array key exists in Javascript](http://stackoverflow.com/questions/1098040/checking-if-an-associative-array-key-exists-in-javascript) –  Dec 27 '13 at 16:06
  • Is this a multiline string? Or is it a json object? What's the exact format and type of the variable you get your data in? – dkellner Dec 27 '13 at 16:08
  • Yep, then it's the easy way, if(x.merchant_id=="whatYouWant") – dkellner Dec 27 '13 at 16:12
  • hey no yaar.I want to search if 'merchant_id' exists,not its value.If(json has merchant_id){// } like this – Ajeesh Dec 27 '13 at 16:13
  • http://stackoverflow.com/a/1098955/1636522, not the answer you are looking for? –  Jan 01 '14 at 06:57

4 Answers4

1

Let's say you have JSON object like this:

var json = {
   amt: "10.00",
   email: "sam@gmail.com",
   merchant_id: "sam",
   mobileNo: "9874563210",
   orderID: "123456",
   passkey: "1234"
}

So now you have to use a loop. E.g.

for(var j in json) { // var j is the key in this loop
   if(j == 'merchant_id') {
      // do something
   }
}
shpyo
  • 221
  • 1
  • 6
0

You can just check the type of of the field.

if (typeof json.property !== 'undefined') {
    //has property
}
  • Can you specify this with my question,so it wil be more clear – Ajeesh Dec 27 '13 at 16:16
  • If you have a JSON formatted like this: var json = { amt: "10.00", email: "sam@gmail.com", merchant_id: "sam", mobileNo: "9874563210", orderID: "123456", passkey: "1234" } and you need to check the existance of the orderID field just do: if (typeof json.orderID!== 'undefined') { //has property } – Mattia Franchetto Dec 27 '13 at 20:35
0

If this is a multiline string like you wrote it, a simple way is:

if(s.indexOf("\nmerchant_id: \"whatever\"\n")>-1) {
    // ...
}

But you can parse it of course, and that's the elegant way. With a json object, you can just refer to the field with a dot, like "obj.merchant_id".

dkellner
  • 8,726
  • 2
  • 49
  • 47
0

For example, try this:

var data = {
   amt: "10.00",
   email: "sam@gmail.com",
   merchant_id: "sam",
   mobileNo: "9874563210",
   orderID: "123456",
   passkey: "1234"
}

if(data.amt == 'something'){
   // do work
}
Ringo
  • 3,795
  • 3
  • 22
  • 37