Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Friday, October 14, 2016

Check if a key exists inside a json object

Check if a key exists inside a json object


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

The above is the JSON object I'm dealing with. I want to check if the 'merchant_id' key exists. I tried the below code, but it's not working. Any way to achieve it?

  

Answer by Zonger for Check if a key exists inside a json object


You can try if(typeof object !== 'undefined')

Answer by anand4tech for Check if a key exists inside a json object


Try this,

if(thisSession.hasOwnProperty('merchant_id')){    }  

the JS Object thisSession should be like

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

you can find the details here

Answer by Paul for Check if a key exists inside a json object


There's several ways to do it, depending on your intent.

thisSession.hasOwnProperty('merchant_id'); will tell you if thisSession has that key itself (i.e. not something it inherits from elsewhere)

"merchant_id" in thisSession will tell you if thisSession has the key at all, regardless of where it got it.

thisSession["merchant_id"] will return false if the key does not exist, or if its value evaluates to false for any reason (e.g. if it's a literal false or the integer 0 and so on).

Answer by Kailas for Check if a key exists inside a json object


Type check will also work as :

if(typeof Obj.property == "undefined"){      // Assign value to the property here      Obj.property = someValue;  }  

Answer by Sam for Check if a key exists inside a json object


I just wanted to point this out even though I'm late to the party. The original question you were trying to find a 'Not IN' essentially which looks like is not supported from the research (2 links below) that I was doing. So if you wanted to do a not:

("merchant_id" in x)  true  ("merchant_id_NotInObject" in x)  false   

I'd recommend just setting that expression == to what you're looking for

if (("merchant_id" in thisSession)==false)  {      // do nothing.  }  else   {      alert("yeah");  }  

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in http://www.w3schools.com/jsref/jsref_operators.asp


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.