transform null to "" in response payload

Hi @Dino-at-Google

Concern: Apigee endpoint is pointing to the target endpoint, when we fire a request to APG, backend is responding with the mentioned payload.

Backend-response:

{
  "name":"xyz",
"age": null,
"street": null

}

My requirement: This is how I want the response back to the consumer

{
  "name":"xyz",
"age": "",
"street": ""

}

Here we need to convert null to ""

Regards,

Ashwith

0 5 498
5 REPLIES 5

Here's what I would do. Use a JS callout and parse the response. Check for each property and replace nulls with empty strings.

function replaceNullWithBlank(input) {
  var output = {};
  for (var prop in input) {
    if (input.hasOwnProperty(prop)) {
      output[prop] = (input[prop] === null) ? "" : input[prop];
    }
  }
  return output;
}


var c = JSON.parse(context.getVariable('response.content'));
var output = replaceNullWithBlank(c);
context.setVariable('response.content', JSON.stringify(output));

Hi @Dino-at-Google,

Thanks for your reply.

Sorry, the code snippet mentioned by you is not working in APIGEE, can you please make sure if it is working on your end.

Regards,

Ashwith

@Dino-at-Google

,

Your code is working only for the mentioned senario in the question earlier.

It is not working if the payload is having a child objects

Example: The response payload may contain multi-level of child objects and arrays

{
    "A": {
        "age": null,
        "name": "ash"
    }
}

You need to make the function recursive to handle that case.

<Javascript name='JS-SwapNullWithBlank' timeLimit='200' >
  <Source>


function swapNullWithBlank(value) {
  return (value === null) ? '' : value;
}


function objectWalker(convert) {
  return function fn(input) {
    var output;
    var t = Object.prototype.toString.apply(input);
    if (t === '[object Object]') {
      output = {};
      for (var prop in input) {
        if (input.hasOwnProperty(prop)) {
          output[prop] = fn(input[prop]);
        }
      }
      return output;
    }
    if (t === '[object Array]') {
      return input.map(function(item) {
        return fn(item);
      });
    }
    return convert(input);
  };
}


var c = JSON.parse(context.getVariable('response.content'));
var convert = objectWalker(swapNullWithBlank);
var output = convert(c);
context.setVariable('response.content', JSON.stringify(output));
  </Source>
</Javascript>
<br>