JSON object in for loop

Abinash
Kilo Contributor

Hi All,

I have a json object inside which der is an array called as items which is used to store the RITM of a request.

But suppose i have 4 RITM for a request how can i dynamically create 4 elements inside the array with these field values.

{

                  "Items": [{

                  "MaterialNumber": "3000016264859",

                  "CustMaterialNumber": "RITM00098",

                  "LineNumber": "1",

                  "HighLevelItem": "",

                  "Quantity": "2",

                  "SmartTrackerItem": [{

                      "Key": "",

                      "Value": ""

                  }]

              }]

}

Thanks in advance.

Abinash Dash

Developer Community

8 REPLIES 8

awessel
Kilo Guru

You can add more to the array by comma-separating the various objects. Something like:



{


        "Items": [


                  {


                            "Material number":"xyz",


                            //object 1 details


                  },


                  {


                            //object 2 details


                  },


                  {


                            //object 3 details


                  }]


}


Abinash
Kilo Contributor

Hi adam,



Thanks for ur reply but creation of ritm is dynamic..so how can i handle


the for loop for this json array so that it shoukd automatically provide me


the resulted format


rokasg
Tera Contributor

Hi Abinash,


Maybe this will help:


obj['items'].push({key:value});


OK, let me take a stab at this. In the script below I'm assuming you're looping through the RITMs associated to a particular Request. Hopefully this helps.



var jsonObj = {};


jsonObj.Items = [];



var ritmRec = new GlideRecord('sc_req_item');


ritmRec.addQuery('request', requestID); //requestID will be the sys_id of the Request in question


ritmRec.query();



while(ritmRec.next()) {


        itemObj = {};


        itemObj.my_details = ritmRec.my_details; //add in all of the mapping that you want here


        jsonObj.Items.push(itemObj);


}



At the end of this the jsonObj object should be what you're looking for. You can use JSON.stringify(jsonObj) to convert it into a string if need be.