How can I transform a JSON Object from target server response into a different JSON object to send to the client?

I have a requirement wherein I am getting a standard JSON response from target server and I have to create JSON object from that response and send it to client application.

The response from target server is as follows:

{
  "results":
  [
    {
      "mail": "employee@gmail.com",
      "uid": "Employee Name",
      "displayName": "Username",
      "givenName": "firstname",
      "sn": "lastname",
      "Employee Id": "12345"
    },
    {
      "mail": "employee2@gmail.com",
      "uid": "Employee2 Name",
      "displayName": "Username2",
      "givenName": "firstname2",
      "sn": "lastname2",
      "Employee Id": "123456"
    }
  ]
}

This is the response that I would like to send to the client:

{
  "apiVersion": "1.0",
  "persons": [
    {
      "Empid": "12345",
      "name": "Employee Name",
      "email": "employee1@gmail.com"
    },
    {
      "Empid": "123456",
      "name": "Employee2 Name",
      "email": "employee2@gmail.com"
    }
  ]
}

I tried to achieve this using Javascript but no success so far.

I should not edit the JSON object returned by the Target server indeed I have to create a new JSON object and set that in response.content.

Best Wishes,

Ashwini

Solved Solved
4 1 5,602
1 ACCEPTED SOLUTION

HI @AshwiniRai -

This is a GREAT usecase for a JavaScript callout.

try the following JS policy code

var respObj = response.content.asJSON;
response.content = '';
response.headers['Content-Type'] = 'application/json';
var body = response.content.asJSON;

body.apiVersion = "1.0";
body.persons = [];

var data = respObj.results;
for(var i in data)
{
     var person = {
         "Empid": data[i]["Employee Id"],
         "name" : data[i]["uid"],
         "email": data[i]["mail"]
     };
     body.persons.push(person);
}

See if this works

View solution in original post

1 REPLY 1

HI @AshwiniRai -

This is a GREAT usecase for a JavaScript callout.

try the following JS policy code

var respObj = response.content.asJSON;
response.content = '';
response.headers['Content-Type'] = 'application/json';
var body = response.content.asJSON;

body.apiVersion = "1.0";
body.persons = [];

var data = respObj.results;
for(var i in data)
{
     var person = {
         "Empid": data[i]["Employee Id"],
         "name" : data[i]["uid"],
         "email": data[i]["mail"]
     };
     body.persons.push(person);
}

See if this works