How to convert String to an Array Object

Surbhi Srivasta
Tera Expert

Hi,

 

I have a hidden variable of type Single Line Text (String) on the catalog form where this variable is currently store output based on internal calculation as shown below

 

Example of data stored in this string variable:

[{"name":"Manager","id":"GUID 1","description":"DESC 1."},{"name":"Pay","id":"GUID2","description":"DESC 2"}]

 

I want to convert this variable value to an Object and format should be exactly the same post conversion as shown above.

 

Reason being, I need the object value to do certain array logic and cannot be done with type as String.

7 REPLIES 7

sunil maddheshi
Tera Guru

@Surbhi Srivasta 

Please try with below code:

var jsonString = g_form.getValue('hidden_var');

try {
    var parsedObj = JSON.parse(jsonString);

    // Example usage: iterate through the array
    parsedObj.forEach(function(item) {
        console.log("Name: " + item.name);
        console.log("ID: " + item.id);
        console.log("Description: " + item.description);
    });

    // If needed, you can also re-stringify it after making changes:
    var updatedString = JSON.stringify(parsedObj);
    g_form.setValue('hidden_var', updatedString);

} catch (e) {
    console.error("Invalid JSON format in hidden_var:", e);
}

Please mark correct/helpful if this helps you!

Ankur Bawiskar
Tera Patron
Tera Patron

@Surbhi Srivasta 

I would like to understand your business requirement here.

It's string so to convert it to object you should use JSON.parse(variableValue)

If my response helped please mark it correct and close the thread so that it benefits future readers.

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

Shivalika
Mega Sage

Hello @Surbhi Srivasta 

 

Please confirm if you checked my answer. Kindly mark my answer as helpful and accept solution if it helped you in anyway. This will help me be recognized for my efforts and also it can move from unsolved bucket to solved bucket. 

 

Regards, 

Shivalika 

 

My LinkedIn - https://www.linkedin.com/in/shivalika-gupta-540346194

 

My youtube - https://youtube.com/playlist?list=PLsHuNzTdkE5Cn4PyS7HdV0Vg8JsfdgQlA&si=0WynLcOwNeE