javascript jquery 检查 json var 是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6105496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:28:45  来源:igfitidea点击:

jquery check if json var exist

javascriptjqueryjsonpush

提问by David

How can I with jquery check to see if a key/value exist in the resulting json after a getJSON?

如何使用 jquery 检查在 getJSON 之后生成的 json 中是否存在键/值?

function myPush(){
    $.getJSON("client.php?action=listen",function(d){
        d.chat_msg = d.chat_msg.replace(/\\"/g, "\"");
        $('#display').prepend(d.chat_msg+'<br />');
        if(d.failed != 'true'){ myPush(); }
    });
}

Basically I need a way to see if d.failed exist and if it = 'true' then do not continue looping pushes.

基本上我需要一种方法来查看 d.failed 是否存在,如果它 = 'true' 然后不要继续循环推送。

回答by beatgammit

You don't need jQuery for this, just JavaScript. You can do it a few ways:

为此,您不需要 jQuery,只需要 JavaScript。您可以通过以下几种方式做到这一点:

  • typeof d.failed- returns the type ('undefined', 'Number', etc)
  • d.hasOwnProperty('failed')- just in case it's inherited
  • 'failed' in d- check if it was ever set (even to undefined)
  • typeof d.failed- 返回类型('undefined'、'Number'等)
  • d.hasOwnProperty('failed')- 以防万一它被继承
  • 'failed' in d- 检查它是否曾经设置过(甚至未定义)

You can also do a check on d.failed: if (d.failed), but this will return false if d.failed is undefined, null, false, or zero. To keep it simple, why not do if (d.failed === 'true')? Why check if it exists? If it's true, just return or set some kind of boolean.

您还可以对 d.failed: 进行检查if (d.failed),但如果 d.failed 未定义、null、false 或零,这将返回 false。为简单起见,为什么不这样做if (d.failed === 'true')?为什么要检查它是否存在?如果是真的,只需返回或设置某种布尔值。

Reference:

参考:

http://www.nczonline.net/blog/2010/07/27/determining-if-an-object-property-exists/

http://www.nczonline.net/blog/2010/07/27/determining-if-an-object-property-exists/

回答by dexter

Found this yesterday. CSS like selectors for JSON

昨天发现了这个。类似 CSS 的 JSON 选择器

http://jsonselect.org/

http://jsonselect.org/

回答by Spoike

You can use a javascript idiom for if-statements like this:

您可以将 javascript 习惯用法用于 if 语句,如下所示:

if (d.failed) {
    // code in here will execute if not undefined or null
}

Simple as that. In your case it should be:

就那么简单。在您的情况下,它应该是:

if (d.failed && d.failed != 'true') {
    myPush();
}

Ironically this reads out as "if d.failed exists and is set to 'true'" as the OP wrote in the question.

具有讽刺意味的是,正如 OP 在问题中所写的那样,这读作“如果 d.failed 存在并设置为‘真’”。