简体   繁体   English

javascript检查JSON键是否存在并显示值

[英]javascript check if JSON key exists and display the value

I've been tinkering with Z-Wave lately and I'm trying to make a page to include/exclude their products. 我最近一直在修改Z-Wave,并且我试图制作一个包含/排除其产品的页面。 But it's not going too well. 但这并不太顺利。 I'm trying to check if a JSON key exists then display it on the page. 我正在尝试检查JSON密钥是否存在,然后将其显示在页面上。 I get 我懂了

TypeError: data.controller is undefined TypeError:data.controller未定义

Here is the code: 这是代码:

window.setInterval(function(){
   getData();
}, 2000);

function getData()
{
var milliseconds = (new Date).getTime();
var time = milliseconds.toString().substr(0, milliseconds.toString().length - 3) ;

$.postJSON( "http://192.168.1.102:8083/ZWaveAPI/Data/" + time, function( data ) {
    if(data.controller.lastExcludedDevice.value) alert("EXCLUDED SOMETHING");
    if(data.controller.lastIncludedDevice.value) alert("INCLUDED SOMETHING");
});   
}

$.postJSON = function(url, data, callback, sync) {

// shift arguments if data argument was omited
if ( jQuery.isFunction( data ) ) {
    sync = sync || callback;
    callback = data;
    data = {};
};
$.ajax({
    type: 'POST',
    url: url,
    data: data,
    dataType: 'json',
    success: callback,
    error: callback,
    async: (sync!=true)
});
};

Json: JSON:

{
  "controller.data.controllerState": {
    "value": 0,
    "type": "int",
    "invalidateTime": 1424781697,
    "updateTime": 1425338938
  },
  "controller.data.lastIncludedDevice": {
    "value": 42,
    "type": "int",
    "invalidateTime": 1424781697,
    "updateTime": 1425338938
  },
  ......

Any help is greatly appreciated. 任何帮助是极大的赞赏。

if the dots are part of the key you need to use the [] notation. 如果点是键的一部分,则需要使用[]表示法。

for example 例如

if (data['controller.data.controllerState'].value) ...

or 要么

if (data['controller.data.lastIncludedDevice'].value) ...

Try this: 尝试这个:

if(data.controller && 
    data.controller.lastExcludedDevice.value) 
    alert("EXCLUDED SOMETHING");

Think of it this way: console.log({}.x) prints "undefined." 可以这样考虑: console.log({}.x) “未定义”。 console.log({}.xy) throws an error. console.log({}.xy)引发错误。 You're allowed to work with undefined but it throws an error if you try to access properties of it. 您可以使用undefined但如果尝试访问它的属性,它将引发错误。

Use the short-circuiting property of && to expedite this check: 使用&&的短路属性可加快此检查:

if(a && a.b && a.b.c && a.b.c.d) {
    console.log("Not an error to print", a.b.c.d);
}{

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM