簡體   English   中英

javascript檢查JSON鍵是否存在並顯示值

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

我最近一直在修改Z-Wave,並且我試圖制作一個包含/排除其產品的頁面。 但這並不太順利。 我正在嘗試檢查JSON密鑰是否存在,然后將其顯示在頁面上。 我懂了

TypeError:data.controller未定義

這是代碼:

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:

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

任何幫助是極大的贊賞。

如果點是鍵的一部分,則需要使用[]表示法。

例如

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

要么

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

嘗試這個:

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

可以這樣考慮: console.log({}.x) “未定義”。 console.log({}.xy)引發錯誤。 您可以使用undefined但如果嘗試訪問它的屬性,它將引發錯誤。

使用&&的短路屬性可加快此檢查:

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