简体   繁体   English

如何检查 NodeJS 中的 JSON 是否为空?

[英]How can I check if a JSON is empty in NodeJS?

I have a function that checks to see whether or not a request has any queries, and does different actions based off that.我有一个函数可以检查请求是否有任何查询,并根据它执行不同的操作。 Currently, I have if(query) do this else something else.目前,我有if(query)做其他事情。 However, it seems that when there is no query data, I end up with a {} JSON object.但是,似乎当没有查询数据时,我最终得到一个{} JSON 对象。 As such, I need to replace if(query) with if(query.isEmpty()) or something of that sort.因此,我需要将if(query)替换为if(query.isEmpty())或类似的东西。 Can anybody explain how I could go about doing this in NodeJS?谁能解释我如何在 NodeJS 中执行此操作? Does the V8 JSON object have any functionality of this sort? V8 JSON 对象是否具有此类功能?

You can use either of these functions:您可以使用以下任一功能:

// This should work in node.js and other ES5 compliant implementations.
function isEmptyObject(obj) {
  return !Object.keys(obj).length;
}

// This should work both there and elsewhere.
function isEmptyObject(obj) {
  for (var key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      return false;
    }
  }
  return true;
}

Example usage:用法示例:

if (isEmptyObject(query)) {
  // There are no queries.
} else {
  // There is at least one query,
  // or at least the query object is not empty.
}

You can use this:你可以使用这个:

var isEmpty = function(obj) {
  return Object.keys(obj).length === 0;
}

or this:或这个:

function isEmpty(obj) {
  return !Object.keys(obj).length > 0;
}

You can also use this:你也可以使用这个:

function isEmpty(obj) {
  for(var prop in obj) {
    if(obj.hasOwnProperty(prop))
      return false;
  }

  return true;
}

If using underscore or jQuery , you can use their isEmpty or isEmptyObject calls.如果使用下划线jQuery ,您可以使用它们的isEmptyisEmptyObject调用。

Object.keys(myObj).length === 0;

As there is need to just check if Object is empty it will be better to directly call a native method Object.keys(myObj).length which returns the array of keys by internally iterating with for..in loop.As Object.hasOwnProperty returns a boolean result based on the property present in an object which itself iterates with for..in loop and will have time complexity O(N2).因为只需要检查 Object 是否为空,所以直接调用本地方法 Object.keys(myObj).length 会更好,它通过在内部迭代 for..in 循环返回键数组。作为Object.hasOwnProperty返回基于对象中存在的属性的布尔结果,该对象本身使用 for..in 循环进行迭代,时间复杂度为 O(N2)。

On the other hand calling a UDF which itself has above two implementations or other will work fine for small object but will block the code which will have severe impact on overall perormance if Object size is large unless nothing else is waiting in the event loop.另一方面,调用本身具有以上两个实现或其他实现的 UDF 对于小对象会很好地工作,但会阻塞代码,如果对象大小很大,将对整体性能产生严重影响,除非事件循环中没有其他等待。

If you have compatibility with Object.keys , and node does have compatibility, you should use that for sure.如果您与Object.keys兼容,并且 node 确实具有兼容性,那么您应该肯定会使用它。

However, if you do not have compatibility, and for any reason using a loop function is out of the question - like me, I used the following solution:但是,如果你没有兼容性,并且出于任何原因使用循环函数是不可能的 - 像我一样,我使用了以下解决方案:

JSON.stringify(obj) === '{}'

Consider this solution a 'last resort' use only if must.将此解决方案视为仅在必要时才使用的“最后手段”。

See in the comments "there are many ways in which this solution is not ideal".在评论中看到“这个解决方案在很多方面都不理想”。

I had a last resort scenario, and it worked perfectly.我有一个不得已的方案,而且效果很好。

My solution:我的解决方案:

let isEmpty = (val) => {
    let typeOfVal = typeof val;
    switch(typeOfVal){
        case 'object':
            return (val.length == 0) || !Object.keys(val).length;
            break;
        case 'string':
            let str = val.trim();
            return str == '' || str == undefined;
            break;
        case 'number':
            return val == '';
            break;
        default:
            return val == '' || val == undefined;
    }
};
console.log(isEmpty([1,2,4,5])); // false
console.log(isEmpty({id: 1, name: "Trung",age: 29})); // false
console.log(isEmpty('TrunvNV')); // false
console.log(isEmpty(8)); // false
console.log(isEmpty('')); // true
console.log(isEmpty('   ')); // true
console.log(isEmpty([])); // true
console.log(isEmpty({})); // true
const isEmpty = (value) => (
    value === undefined ||
    value === null ||
    (typeof value === 'object' && Object.keys(value).length === 0) ||
    (typeof value === 'string' && value.trim().length === 0)
  )

module.exports = isEmpty;

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

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