Hi All,
I need to search and replace one tag name and value in JSON object response from the target system.
Here is an example of target response:
i need to replace the “ErrorCode” to “ResponseCode” and “1000” to “200”.
From:
{ "Status": "PASSED", "ErrorCode": "1000"}
To:
{ "Status": "PASSED", "ResponseCode": "200"}
I tried a few examples posted on stackoverflow but couldn’t find anything that will do a deep search and replace.
Any help would be appreciated.
1 Like
The Very simple way to satisfy your particular case in a JS callout within Apigee Edge is:
var c = JSON.parse(context.getVariable('response.content'));
c.ResponseCode = 200; // or "200", if you want string
delete c.ErrorCode;
context.setVariable('response.content', JSON.stringify(c));
That satisfies your particular case. But I think you want something more complex.
Can you give two additional examples - input & desired output - to illustrate what you mean by “Deep search and replace”?
1 Like
If you want apply regex, then you can do like this
var str = ‘{ “Status”: “PASSED”, “ErrorCode”: “1000”}’;
var output = str.replace( new RegExp(/“errorcode”:\s*“[^”]+?[^/“]+”/ig),‘“ResponseCode”: “200”’);
console.log(output);
I have used a similar solution as suggested by @Dino, and it works fine. Adding a new property to JSON and deleting the old one.
1 Like
Yes, That’s clear way of doing addition and deletion of objejcts.