[javascript] 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. However, it seems that when there is no query data, I end up with a {} JSON object. As such, I need to replace if(query) with if(query.isEmpty()) or something of that sort. Can anybody explain how I could go about doing this in NodeJS? Does the V8 JSON object have any functionality of this sort?

This question is related to javascript json node.js v8

The answer is


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;

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.


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).

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.


If you have compatibility with Object.keys, and node does have compatibility, you should use that for sure.

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to v8

How to get a microtime in Node.js? How can I check if a JSON is empty in NodeJS? How to efficiently check if variable is Array or Object (in NodeJS & V8)? Node.js: for each … in not working Executing JavaScript without a browser? What is Node.js?