Script to build JSON

maryc
Tera Contributor

Hi,

 

How do I build a JSON request for a Webservice call to be in this format?

 

{
                "Address_Billing":
                {
                              "Description": "{DESCRIPTION}",
                              "CompanyName": "{COMPANYNAME}",
                              "Name_First": "{NAME_FIRST}",
                              "Name_Last": "{NAME_LAST}",
                              "StreetAddress_Line1": "{STREET_ADDRESS}",
                              "StreetAddress_Line2": "{STREET_ADDRESS_SECONDARY}",
                              "City": "{CITYNAME}",
                              "StateOrProvince": "{STATEABBREVIATIONCODE}",
                              "PostalCode": "{ZIPCODE}",
                              "Country": "US",
                              "Email": "{EMAILADDRESS}",
                              "Telephone": "{PHONENUMBER}"
                },
                "Address_Shipping":
                {
                              "Description": "{DESCRIPTION}",
                              "CompanyName": "{COMPANYNAME}",
                              "Name_First": "{NAME_FIRST}",
                              "Name_Last": "{NAME_LAST}",
                              "StreetAddress_Line1": "{STREET_ADDRESS}",
                              "StreetAddress_Line2": "{STREET_ADDRESS_SECONDARY}",
                              "City": "{CITYNAME}",
                              "StateOrProvince": "{STATEABBREVIATIONCODE}",
                              "PostalCode": "{ZIPCODE}",
                              "Country": "US",
                              "Email": "{EMAILADDRESS}",
                              "Telephone": "{PHONENUMBER}"
                },
                "ItemsRequested":[
                {
                                            "ProductID": "{PRODUCTID}",
                                            "Quantity": "{QUANTITYREQUESTED}"
               }

          ],
                "Comments": "{COMMENTS}",
                "PONumber": "{YOUR_PO_NUMBER}",
    
 }

Thanks in advance

1 ACCEPTED SOLUTION

400 means that the target system didn't like your request.  I made a few modifications in the below script.  If the below doesn't work you will need to work with the owners of the target system to see what additional logging within their system is available to help you understand what's wrong with your request.

Summary of changes I made:

  • Added request header Content-Type to tell the target system that you are sending Json
  • Renamed request to requestBody so its easier to read
  • Renamed request1 to restMessage so its easier to read
  • removed the gs.print() statement I had in previously

I would also suggest you look at the ServiceNow logs to see if there are any additional errors from your logging of the resposeBody

 

var restMessage = new sn_ws.RESTMessageV2('Order Request', 'Post');
restMessage.setAuthentication("basic", "My Auth");
restMessage.setRequestHeader("Accept","application/json");
restMessage.setRequestHeader("Content-Type","application/json")

var requestBody = {}
var addressBilling = {};
var addressShipping = {};
var itemsRequested = [];

addressBilling.Description = "A";
addressBilling.CompanyName = "B";
addressBilling.Name_First = "C";
addressBilling.Name_Last = "D";
addressBilling.StreetAddress_Line1 = "E";
addressBilling.StreetAddress_Line2 = "F";
addressBilling.City = "G";
addressBilling.StateOrProvince = "FL";
addressBilling.PostalCode = "20173";
addressBilling.Country = "US";
addressBilling.Email = "abc@abc.com";
addressBilling.Telephone = "1234567890";

addressShipping.Description = "A";
addressShipping.CompanyName = "B";
addressShipping.Name_First = "C";
addressShipping.Name_Last = "D";
addressShipping.StreetAddress_Line1 = "E";
addressShipping.StreetAddress_Line2 = "F";
addressShipping.City = "G";
addressShipping.StateOrProvince = "FL";
addressShipping.PostalCode = "20173";
addressShipping.Country = "US";
addressShipping.Email = "abc@abc.com";
addressShipping.Telephone = "1234567890";


var itemRequested = {};
itemRequested.ProductID = "844152"
itemRequested.Quantity = "1";
itemRequested.AllowBackOrder="false";
itemsRequested.push(itemRequested);


requestBody.Address_Billing = addressBilling;
requestBody.Address_Shipping = addressShipping;
requestBody.ItemsRequested = itemsRequested;
requestBody.Comments = "Comments";
requestBody.PONumber = "PO Number";
requestBody.PromotionCode = "";

//Encode as JSON
requestBody = new global.JSON().encode(requestBody);
restMessage.setRequestBody(requestBody);

var response = restMessage.execute();
var responseBody = response.getBody();
var httpStatus = response.getStatusCode();
gs.log(" responsebody "+responseBody);
gs.log(" httpStatus "+httpStatus);

View solution in original post

6 REPLIES 6

Michael Ritchie
ServiceNow Employee
ServiceNow Employee

Here is a quick snippet of code that should get you going.  Things to note:

{} declares an object

[] declares an array

var request = {}
var addressBilling = {};
var addressShipping = {};
var itemsRequested = [];

addressBilling.Description = "Description";
addressBilling.CompanyName = "CompanyName";

addressShipping.Description = "Description";
addressShipping.CompanyName = "CompanyName";

var itemRequested = {};
itemRequested.ProductID = "ProductID1"
itemRequested.Quantity = "1";
itemsRequested.push(itemRequested);

var itemRequested = {};
itemRequested.ProductID = "ProductID2"
itemRequested.Quantity = "2";
itemsRequested.push(itemRequested);

request.Address_Billing = addressBilling;
request.Address_Shipping = addressShipping;
request.ItemsRequested = itemsRequested;
request.Comments = "Comments";
request.PONumber = "PO Number";

//Encode as JSON
request = new global.JSON().encode(request);

gs.print(request);

Executing this via background script produces the following:

*** Script: {"Address_Billing":{"CompanyName":"CompanyName","Description":"Description"},"Address_Shipping":{"CompanyName":"CompanyName","Description":"Description"},"Comments":"Comments","ItemsRequested":[{"ProductID":"ProductID1","Quantity":"1"},{"ProductID":"ProductID2","Quantity":"2"}],"PONumber":"PO Number"}

maryc
Tera Contributor

Hello Michael,

I am trying this script and I get a 400 error. Any idea why?

 

var request1 = new sn_ws.RESTMessageV2('Order Request', 'Post');
request1.setAuthentication("basic", "My Auth");
request1.setRequestHeader("Accept","application/json"); 

	var request = {}
	var addressBilling = {};
	var addressShipping = {};
	var itemsRequested = [];

	addressBilling.Description = "A";
	addressBilling.CompanyName = "B";
	addressBilling.Name_First = "C";
	addressBilling.Name_Last = "D";
	addressBilling.StreetAddress_Line1 = "E";
	addressBilling.StreetAddress_Line2 = "F";
	addressBilling.City = "G";
	addressBilling.StateOrProvince = "FL";
        addressBilling.PostalCode = "20173";
	addressBilling.Country = "US";
	addressBilling.Email = "abc@abc.com";
	addressBilling.Telephone = "1234567890";

	addressShipping.Description = "A";
	addressShipping.CompanyName = "B";
	addressShipping.Name_First = "C";
	addressShipping.Name_Last = "D";
	addressShipping.StreetAddress_Line1 = "E";
	addressShipping.StreetAddress_Line2 = "F";
	addressShipping.City = "G";
	addressShipping.StateOrProvince = "FL";
        addressShipping.PostalCode = "20173";
	addressShipping.Country = "US";
	addressShipping.Email = "abc@abc.com";
	addressShipping.Telephone = "1234567890";


	var itemRequested = {};
	itemRequested.ProductID = "844152"
	itemRequested.Quantity = "1";
	itemRequested.AllowBackOrder="false";
	itemsRequested.push(itemRequested);


	request.Address_Billing = addressBilling;
	request.Address_Shipping = addressShipping;
	request.ItemsRequested = itemsRequested;
	request.Comments = "Comments";
	request.PONumber = "PO Number";
	request.PromotionCode = "";

	//Encode as JSON
	request = new global.JSON().encode(request);
        request1.setRequestBody(request);
	gs.print(request);

	 var response = request1.execute();
	 var responseBody = response.getBody();
	 var httpStatus = response.getStatusCode();
	 gs.log(" responsebody "+responseBody);
	 gs.log(" httpStatus "+httpStatus);
 

 

 

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Request Error</title>
    <style>BODY { color: #000000; background-color: white; font-family: Verdana; margin-left: 0px; margin-top: 0px; } #content { margin-left: 30px; font-size: .70em; padding-bottom: 2em; } A:link { color: #336699; font-weight: bold; text-decoration: underline; } A:visited { color: #6699cc; font-weight: bold; text-decoration: underline; } A:active { color: #336699; font-weight: bold; text-decoration: underline; } .heading1 { background-color: #003366; border-bottom: #336699 6px solid; color: #ffffff; font-family: Tahoma; font-size: 26px; font-weight: normal;margin: 0em 0em 10px -20px; padding-bottom: 8px; padding-left: 30px;padding-top: 16px;} pre { font-size:small; background-color: #e5e5cc; padding: 5px; font-family: Courier New; margin-top: 0px; border: 1px #f0f0e0 solid; white-space: pre-wrap; white-space: -pre-wrap; word-wrap: break-word; } table { border-collapse: collapse; border-spacing: 0px; font-family: Verdana;} table th { border-right: 2px white solid; border-bottom: 2px white solid; font-weight: bold; background-color: #cecf9c;} table td { border-right: 2px white solid; border-bottom: 2px white solid; background-color: #e5e5cc;}</style>
  </head>
  <body>
    <div id="content">
      <p class="heading1">Request Error</p>
      <p>The server encountered an error processing the request. See server logs for more details.</p>
    </div>
  </body>
</html>
*** Script:  httpStatus 400

400 means that the target system didn't like your request.  I made a few modifications in the below script.  If the below doesn't work you will need to work with the owners of the target system to see what additional logging within their system is available to help you understand what's wrong with your request.

Summary of changes I made:

  • Added request header Content-Type to tell the target system that you are sending Json
  • Renamed request to requestBody so its easier to read
  • Renamed request1 to restMessage so its easier to read
  • removed the gs.print() statement I had in previously

I would also suggest you look at the ServiceNow logs to see if there are any additional errors from your logging of the resposeBody

 

var restMessage = new sn_ws.RESTMessageV2('Order Request', 'Post');
restMessage.setAuthentication("basic", "My Auth");
restMessage.setRequestHeader("Accept","application/json");
restMessage.setRequestHeader("Content-Type","application/json")

var requestBody = {}
var addressBilling = {};
var addressShipping = {};
var itemsRequested = [];

addressBilling.Description = "A";
addressBilling.CompanyName = "B";
addressBilling.Name_First = "C";
addressBilling.Name_Last = "D";
addressBilling.StreetAddress_Line1 = "E";
addressBilling.StreetAddress_Line2 = "F";
addressBilling.City = "G";
addressBilling.StateOrProvince = "FL";
addressBilling.PostalCode = "20173";
addressBilling.Country = "US";
addressBilling.Email = "abc@abc.com";
addressBilling.Telephone = "1234567890";

addressShipping.Description = "A";
addressShipping.CompanyName = "B";
addressShipping.Name_First = "C";
addressShipping.Name_Last = "D";
addressShipping.StreetAddress_Line1 = "E";
addressShipping.StreetAddress_Line2 = "F";
addressShipping.City = "G";
addressShipping.StateOrProvince = "FL";
addressShipping.PostalCode = "20173";
addressShipping.Country = "US";
addressShipping.Email = "abc@abc.com";
addressShipping.Telephone = "1234567890";


var itemRequested = {};
itemRequested.ProductID = "844152"
itemRequested.Quantity = "1";
itemRequested.AllowBackOrder="false";
itemsRequested.push(itemRequested);


requestBody.Address_Billing = addressBilling;
requestBody.Address_Shipping = addressShipping;
requestBody.ItemsRequested = itemsRequested;
requestBody.Comments = "Comments";
requestBody.PONumber = "PO Number";
requestBody.PromotionCode = "";

//Encode as JSON
requestBody = new global.JSON().encode(requestBody);
restMessage.setRequestBody(requestBody);

var response = restMessage.execute();
var responseBody = response.getBody();
var httpStatus = response.getStatusCode();
gs.log(" responsebody "+responseBody);
gs.log(" httpStatus "+httpStatus);

It worked.Thank you so much Michael.