How to check Object is Empty Or not

Sironi
Kilo Sage

Hi All,

Can you please suggest me how to check Object is empty or not,
If JSON is empty then complier should not go till " return JSON.stringify(arr);" 

if JSON is not empty then complier  should touch return JSON.stringify(arr); line in Code.

 

issue: script include returning error message like "Empty JSON string", If JSON is empty then 

Script include :

{

var arr=[];
for(var i=0;i<list.length;i++)

obj={

name: list[i].name,

id:list[i].id

},

arr.push(obj);

}

return JSON.stringify(arr);

},


to control this I tried below method to check JSON is empty or not ? but not working

1. Object.Keys(JSON.stringify(arr)).length===0

2. if(JSON.stringify(arr)==='{}')

 

Please suggest me , how to fix this

7 REPLIES 7

Sandeep Rajput
Tera Patron
Tera Patron

@Sironi Try updating the script as follows.

 

 

var arr = [];
    for (var i = 0; i < list.length; i++) {
        var obj = {

                name: list[i].name,

                id: list[i].id

            };

            arr.push(obj);
    }
	if(arr.length>0){
		return JSON.stringify(arr);
	}
	return '';    //Returns empty string if no elements in array

 

It returns string array only if it has some elements else it returns an empty string. 

Hi,

Thanks for your reply,

here  list should be some variable/array type object right ?

list

so  List what it will represents ? are we taking any Default predefined length ? 

Community Alums
Not applicable

Hi @Sironi ,

Please try below script 

var arr = [];
for (var i = 0; i < list.length; i++){
    var obj = {
        name: list[i].name,
        id: list[i].id
    };
    arr.push(obj);
}
if(arr.length <= 0){
	gs.log("Array Length is less than zero");
}else{
	gs.log("Array Length is greater than zero");
}
gs.log(JSON.stringify(arr));

Please mark my answer correct and helpful if this works for you

Thanks and Regards 

Sarthak