Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

How to store json array values into variables using loop?

SK36
Tera Contributor

Request is from 3rd party tool like : "weekoff" : "[{saturday, sunday}]";

then, I have 7 checkboxes named (monday,tuesday,wednesday,thursday,friday,saturday,sunday) on catelog item.

and I want to check saturday & sunday check boxes. How to achieve this?

How to write for loop on this?

1 ACCEPTED SOLUTION

Brad Bowman
Kilo Patron
Kilo Patron

I'm assuming your sample text is part of a larger object, so I've used that in my mock up with a hard-coded object.  If not, you can remove the first 'for' and 'if' blocks.  If the value of "weekoff" is truly formatted as above (curly brackets inside of an array, a space after the comma), you'll need the 'replace' lines to convert this to an actual array before the second loop, otherwise there might be a better way to work with the value you're getting, but this works (onLoad Catalog Client Script in this example)...

var obj = {"name1" : "value1", "weekoff" : "[{saturday, sunday}]"};
	for (var field in obj) {
		if (field == "weekoff") {
			var days = obj.weekoff;
			days = days.replace("[", "");
			days = days.replace("{", "");
			days = days.replace("]", "");
			days = days.replace("}", "");
			var daysArr = days.split(", ");
			for (var i=0; i < daysArr.length; i++) {
				g_form.setValue(daysArr[i], true);
			}
		}
	}

View solution in original post

4 REPLIES 4

Brad Bowman
Kilo Patron
Kilo Patron

I'm assuming your sample text is part of a larger object, so I've used that in my mock up with a hard-coded object.  If not, you can remove the first 'for' and 'if' blocks.  If the value of "weekoff" is truly formatted as above (curly brackets inside of an array, a space after the comma), you'll need the 'replace' lines to convert this to an actual array before the second loop, otherwise there might be a better way to work with the value you're getting, but this works (onLoad Catalog Client Script in this example)...

var obj = {"name1" : "value1", "weekoff" : "[{saturday, sunday}]"};
	for (var field in obj) {
		if (field == "weekoff") {
			var days = obj.weekoff;
			days = days.replace("[", "");
			days = days.replace("{", "");
			days = days.replace("]", "");
			days = days.replace("}", "");
			var daysArr = days.split(", ");
			for (var i=0; i < daysArr.length; i++) {
				g_form.setValue(daysArr[i], true);
			}
		}
	}

Thanks a lot, brad. its working.

You are welcome!

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

So what script did you start?

Regards
Ankur

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