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>
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.
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().
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With