JavaScript - 检查 JSON 中是否有特定键可用

JavaScript - Check if a particular key is available in the JSON

本文关键字:是否 检查 JSON JavaScript      更新时间:2023-09-26

我正在从实时流数据中检索JSON。对于第一次调用,我正在获得带有时间和值的数据集数组。但在第二个 JSON 数据集数组中为空。我想检查数据集数组是否包含时间键。

首次调用后检索的 JSON:

 {
  "activities-heart-intraday": {
    "dataset": [{
        "time": "00:00:00",
        "value": 91
    }, {
        "time": "00:01:00",
        "value": 92
    }, {
        "time": "00:02:00",
        "value": 92
    }],
    "datasetInterval": 1,
    "datasetType": "second"
  }
}

第二次调用后检索到的 JSON:

{
  "activities-heart-intraday": {
    "dataset": [],
    "datasetInterval": 1,
    "datasetType": "second"
  }
}

我在做

var value = JSON.parse(data);
if (value.hasOwnProperty('time')) {
   console.log("here");
} 

以检查 JSON 中是否存在时间键,但它不起作用。

如何检查 json 中的数组中是否存在特定键?

首先,您必须检查dataset是否不是一个空数组。然后检查是否已定义time

这可以通过以下方式解决:

if (dataset[0] !== undefined && dataset[0].time !== undefined)

或只是:

if (dataset[0] && dataset[0].time)

如果要循环访问数组:

dataset.forEach(function (data) {
   if (data.time) {
       // your code
   } 
});

数据有一个数据集数组,因此我们需要首先检查数组是否存在,然后检查其中一个数组成员是否具有 time 属性

if( data.hasOwnProperty('dataset') && data.dataset.length != 0){    
  if( data.dataset[0].hasOwnProperty('time')){
    console.log('true');    
  }
}

由于在JS中,您无法通过点表示法本地设置和访问带有" -"字符的对象属性,因此您可以将它们定义为字符串并使用括号表示法来设置和访问它们。所以你可以像这样做检查

data["activities-heart-intraday"].dataset.length > 0 && data["activities-heart-intraday"].dataset.every(e => !!e.time);

我真的无法从您的问题中分辨出data应该是什么,但如果它是整个 JSON 对象,那么最简单的方法是:

if(data["activities-heart-intraday"]["dataset"][0]["time"])
  console.log('time is set)

但要小心!例如,如果未设置dataset,您将收到一个错误,提示您正在尝试从undefined获取密钥time并且代码将崩溃。我建议使用简单的递归函数,如下所示:

function is_there_the_key(json, keys){
  if(keys.length == 0)
    return true           //we used the whole array, and every key was found
  let key = keys.shift()  //pop(get and remove) the first string from keys
  if(!json[key]){
    console.log(key + ' not found')
    return false          //one of the keys doesn't exist there
  }
  return is_there_the_key(json[key], keys)
}

无论你是true还是false返回,它们都会浮出水面。

作为json参数,您传递要搜索的 json。

作为keys参数,您可以按键的顺序传递键的数组(主要是字符串)。例如:

if(is_there_the_key(data, ["activities-heart-intraday", "dataset", 0, "time"])
  //we found the key, do something here