Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 862
thisissami Avatar asked Jul 14 '12 03:07

thisissami


People also ask

How do I check if a JSON object is empty in node JS?

Use the Object. entries() function. It returns an array containing the object's enumerable properties. If it returns an empty array, it means the object does not have any enumerable property, which in turn means it is empty.

How do you check if a JSON file is empty or not?

path. getsize(path) to find file size of a file. You do not have to read file at all. If JSON file is just 2 bytes, "[]" or "{}", it is an empty JSON object.

Can JSON key empty?

Tl;dr Yes it is.


2 Answers

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. } 
like image 190
PleaseStand Avatar answered Oct 02 '22 10:10

PleaseStand


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.

like image 29
ali haider Avatar answered Oct 02 '22 09:10

ali haider