检查密钥是否存在于json对象中

本文翻译自:Check if a key exists inside a json objectphp

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. 上面是我正在处理的JSON对象。 I want to check if the 'merchant_id' key exists. 我想检查'merchant_id'密钥是否存在。 I tried the below code, but it's not working. 我尝试了如下代码,但没法正常工做。 Any way to achieve it? 有办法实现吗? express

<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>

#1楼

参考:https://stackoom.com/question/1PI71/检查密钥是否存在于json对象中json


#2楼

您能够尝试if(typeof object !== 'undefined') less


#3楼

Try this, 尝试这个, ide

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

}

the JS Object thisSession should be like JS对象thisSession应该像 this

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

you can find the details here 您能够在这里找到详细信息 lua


#4楼

There's several ways to do it, depending on your intent. 有多种方法能够完成此操做,具体取决于您的意图。 .net

thisSession.hasOwnProperty('merchant_id'); will tell you if thisSession has that key itself (ie not something it inherits from elsewhere) 会告诉您thisSession是否具备该密钥自己(即不是它从其余地方继承来的) 翻译

"merchant_id" in thisSession will tell you if thisSession has the key at all, regardless of where it got it. "merchant_id" in thisSession将告诉您thisSession是否彻底具备密钥,不管它从何处获取。 code

thisSession["merchant_id"] will return false if the key does not exist, or if its value evaluates to false for any reason (eg if it's a literal false or the integer 0 and so on). 若是键不存在,或者键的值因为任何缘由(例如,它是字面值false或整数0,依此类推),则thisSession["merchant_id"]将返回false。


#5楼

Type check also works : 类型检查也能够:

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

#6楼

(I 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. 您试图从本质上查找“ Not IN”的原始问题。 It looks like is not supported from the research (2 links below) that I was doing. 我正在作的研究彷佛不支持(下面2个连接)。

So if you wanted to do a 'Not In': 所以,若是您想执行“不参加”活动:

("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 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/in http://www.w3schools.com/jsref/jsref_operators.asp