Parsing complex JSON in script

Shreyoshi1
Giga Contributor

Hi,

I have to read a complex JSON dynamically in my code which is a script being used in Virtual Agent. The JSON looks something like below:

{
"name": "Shreyoshi",
"description": "My Name",
"family": [
{
"id": "1",
"relationship": "Father",
},
{
"id": "2",
"relationship": "Mother",
}
]
}

In my script after reading the JSON, I am doing the below:

var obj = new global.JSON().decode(reqTemp.toString());
gs.info("JSON String " + obj);
for ( var key in obj)
{
gs.info(" key is : " + key + " and value for key is " + obj[key]);
}
For the key="family", the value is being printed as [object Object], how can I read the JSON within the "family" array dynamically, without having to know the exact key?
 
Can anyone help me on this please.
 
Thanks

 

10 REPLIES 10

MrMuhammad
Giga Sage

Hi Shreyoshi,

To get the keys you can use below

var keys = Object.keys(JSON Object Here);

gs.info('Keys :' + keys);

For detailed information, please refer below article

JSON Encoding 

Thanks & Regards,

Sharjeel

Regards,
Muhammad

Thanks but I dont need the key, I want the value inside the array which is being printed as Object

Try this.

var obj = global.JSON.parse(reqTemp);

gs.info("JSON String " + obj);


for ( var key in obj){
  gs.info(" Value of Family id is - " + obj.family[key].id);
  gs.info(" Value of Family relationship is - " + obj.family[key].relationship);
}

Regards,
Muhammad

Sajilal
Mega Sage

Hi,

An ideal way to parse JSON and get the value.

var text = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';
var obj = JSON.parse(text);
gs.print(obj.birth);

In your case obj.family.id; etc

Hope this helps!

Please Mark as ✅ Correct if this solves your issue and also mark ???? Helpful if it helps resolve your problem.

Thanks,
Saji