How to read key-value as a map or pair from a JSON

Shreyoshi1
Giga Contributor

Hi,

I have a JSON stored in a column of a table . I want to read it in script task of Virtual Agent Topic. I am doing the below but unable to get the keys or value, can anyone help with this please?

var obj = new global.JSON().encode(reqTemp); //reqTemp is the field read from the GlideRecord
for ( var key in obj)
{
     gs.info(" key is : " + key + " and value for key is " + obj[key]);
}
 
It just prints replaceAll as the key
1 ACCEPTED SOLUTION

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

Try this alternative way

you need to use decode in order to convert that json string as object

var obj = new global.JSON().decode(reqTemp.toString());

for ( var key in obj)
{
     gs.info(" key is : " + key + " and value for key is " + obj[key]);
}

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

View solution in original post

7 REPLIES 7

Hitoshi Ozawa
Giga Sage
Giga Sage

JSON().encode is depreciated.

The encode() and decode() methods are deprecated. Use the JavaScript JSON object instead.

https://developer.servicenow.com/dev.do#!/reference/api/orlando/server_legacy/c_JSONAPI

Do you have a column of type String?

If so, you'll need to parse().

 

var jsonString = '{"key1" : "value1","key2" : "value2","key3" : "value3"}';
var obj = JSON.parse(jsonString);
for ( var key in obj)
{
     gs.info(" key is : " + key + " and value for key is " + obj[key]);
}

 Result:

*** Script:  key is : key1 and value for key is value1
*** Script:  key is : key2 and value for key is value2
*** Script:  key is : key3 and value for key is value3

Seems like Ankur beat me to the posting the reply. Anyways, encode() and decode() is depreciated and shouldn't be used.

Somehow it still shows in developer site; seems then time to update that

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader