Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a key exists inside a JSON object

amt: "10.00" email: "[email protected]" 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?

<script> window.onload = function getApp() {   var thisSession = JSON.parse('<?php echo json_encode($_POST); ?>');   //console.log(thisSession);   if (!("merchant_id" in thisSession)==0)   {     // do nothing.   }   else    {     alert("yeah");   } } </script> 
like image 434
Ajeesh Avatar asked Dec 27 '13 16:12

Ajeesh


People also ask

How do you check if a key is present in a JSON object?

has() method – Class JsonObject. This is the convenience method that can be used to check of a property/member with the specified key is present in the JsonObject or not. This method returns true if the member with specified key exists, otherwise it returns false.

How do you check if a key exists in JSON object and get its value?

Use below code to find key is exist or not in JsonObject . has("key") method is used to find keys in JsonObject . If you are using optString("key") method to get String value then don't worry about keys are existing or not in the JsonObject . Note that you can check only root keys with has(). Get values with get().

How do you check if a key exists in an object?

There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.


1 Answers

Try this,

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

the JS Object thisSession should be like

{ amt: "10.00", email: "[email protected]", merchant_id: "sam", mobileNo: "9874563210", orderID: "123456", passkey: "1234" } 

you can find the details here

like image 61
Anand Jha Avatar answered Sep 17 '22 13:09

Anand Jha