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

Community Alums
Not applicable

BillMartin
Mega Sage

Hi @Surbhi Srivasta ,

 

That’s a great question you’ve raised. The code I developed demonstrates a client-to-server interaction implemented using Object-Oriented Programming and adheres to the SOLID principles of software architecture. It’s designed to handle multiple scenarios, including converting strings to objects and vice versa. I invite you to watch the demo to see it in action and understand how these principles come together in a practical implementation.

 

Robert H
Mega Sage

Hello @Surbhi Srivasta ,

 

You can use the JSON interface, like this:

var value = g_form.getValue('PUT YOUR VARIABLE NAME HERE');
var valueObject = JSON.parse(value);

valueObject.forEach(element => {
	console.log(JSON.stringify(element));
	console.log(element.name);
});

Output:

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

 

Regards,

Robert

Shivalika
Mega Sage

Hello @Surbhi Srivasta 

 

You can just use JSON.parse() 

 

Refer below screenshot:-

 

Shivalika_0-1743919270295.png

 

 

var jsonString = '[{"name":"Manager","id":"GUID 1","description":"DESC 1."},{"name":"Pay","id":"GUID2","description":"DESC 2"}]';

// Convert to JavaScript object (array)
var parsedArray = JSON.parse(jsonString);

// Example: Loop through the array
for (var i = 0; i < parsedArray.length; i++) {
var item = parsedArray[i];
gs.info('Name: ' + item.name + ', ID: ' + item.id + ', Description: ' + item.description);
}

 

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

 

Regards,

 

Shivalika 

 

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

 

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