Check if elements exists in Nested JSON

Khanna Ji
Tera Guru

Hi All,

I am trying to check if element exists in Nested JSON object but it's not working. I have tried hasOwnProperty method and it's working for direct JSON but not working for nested one as show below.

var response='{"short_description":"Test","description":{"status":"New"}}';
var obj = new global.JSON().decode(response)
if (obj.hasOwnProperty('status'))
{
gs.print('found');                      
}

 

@franktate @Chuck Tomasi @Mark Roethof - Tagged you to see if you can help

1 ACCEPTED SOLUTION

Upender Kumar
Mega Sage

For this you have to create a recursive function. Try below code.

 

var response='{"short_description":"Test","description":{"status":"New"}}';
	var obj = new global.JSON().decode(response);
	gs.print(CheckKey('status',obj));
	function CheckKey(key,obj){
		for (var name in obj) {

			if(typeof obj[name]=='object'){
				var newObj=obj[name];
				return CheckKey(key,newObj)
			}
			else if(name==key){
				return true;
			}
		}
		return false;
	}

View solution in original post

6 REPLIES 6

My bad, in a hurry I forgot to declare the object before invoking a function of a class.

Thank you.

Frank Tate
Giga Guru
Giga Guru

Here's an answer feom stackoverflow: https://stackoverflow.com/questions/17957564/how-do-i-check-to-see-if-an-object-or-its-children-sub-...

One of the keys to programming is to try to identify the generic case of whatever problem you're trying to solve. In this instance, while you're dealing with JSON, the solution is all just about objects and "child" objects. A web search that includes "JSON" might not have any good results, but the above is the first hit I got googling "javascript does object or its children have property".

Frank