Construct a JSON Payload in javascript

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-18-2019 05:42 PM
Hello!
I have to construct a JSON payload that looks like this, can someone help me? I am able to get the straight forward one but unable to build a nested payload. How do I go about adding more nested keys, one inside the other. Also some of the keys and values are dynamic and have to replaced with variables.
https://community.servicenow.com/community?id=community_question&sys_id=26807b5cdbfcd34c7b337a9e0f961937
This link helps a little but unable to understand how to build keys one within another.
{
"format_version": "0.2.19",
"alliances": {
"xyz": {
"environments": {
"prd": {
"teams": {
"abc": {
"action": "edit",
"team": "abc",
"projects": {
"prjabc": {
"project": "prjabc",
"cost_center": "0",
"custom_iam_policies": [],
"iam": {
"view_group_email_name": "abc@email.com",
"sre_admin_group_email_name": "xyz@email.com"
},
"allowed_apis": [
"api1",
"api2"
],
"networks": {
"network1": {
"flags": [
"VM"
],
"region": "sample-region",
"preferred-suffix": "routable"
}
}
}
}
}
}
}
}
}
}
}
- Labels:
-
Scripting and Coding
-
Team Development

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-18-2019 05:53 PM
The easiest way to build JSON is to first build a JavaScript object. It appears that you already have a JSON object. Then just call JSON.stringify;
var json = JSON.stringify(obj);
You just need to make sure that your object does not contain any GlideRecords or GlideElements. Only strings, numbers, arrays and other nested objects (as in your example).

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-18-2019 06:01 PM
My requirement is, a user fills in a catalog form and on submission I need to take values from the variables the user filled and create a JSON file that looks like the one I posted in the question. I do not have a JSON object I believe, have to pull values from the variables and build it.

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-18-2019 10:10 PM
Did you try it? JSON is available as a javascript object both server and client side.
https://www.w3schools.com/js/js_json_intro.asp
Like Giles said, just build an object and stringify it.
var obj = {};
obj.prop1 = {};
obj.prop2 = "Test";
obj.prop1.subprop = {};
and so on

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-18-2019 10:12 PM
Hi
Can you share the script that you tried?