json search and replace

Hi All,

I need to search for certain text in JSON object response from the target system and replace it with the something else before the response gets out to proxy caller.

Here is an example of target response:

{ “d”: { “results”: [{ “__metadata”: { “uri”: “https://original.uri/AccountCollection(‘0088’)”, “type”: “c4codata.Account”, “etag”: “W/"datetimeoffset’2016-08-03T18%3A18%3A30.4003730Z’"” }, “POBoxDeviatingRegionCode”: “”, “RoleCode”: “B00002”, “AccountContactRelationship”: { “__deferred”: { “uri”: “https://original.uri/AccountCollection(‘0088’)/AccountContactRelationship” } }, “AccountNotes”: { “__deferred”: { “uri”: “https://original.uri/AccountCollection(‘0088’)/AccountNotes” } } }] } }

In the javascript policy, I want to replace ALL occurances of https://original.uri with https://myproxyendpoint.apigee.net

I tried a few examples posted on stackoverflow but couldn’t find anything that will do a deep search and replace. I tried using the /g regex expression which doesn’t seem to be supported by the JS policy on edge.

Any help would be appreciated.

Thanks!

1 Like

@Vivek Dahiya

For Searching a particular text in JSON or in XML and replacing it with other text is possible through JS Policy in Apigee.

You can use regex expression using global search(g) which is supported by the JS policy on edge.

@Vivek Dahiya

The below snippet might help you

var regex = new RegExp(‘https://original.uri’, ‘g’);

var source=source.replace(regex,https://myproxyendpoint.apigee.net);

1 Like

Hi,

Add replace all function to the string utitlity prototype ,

String.prototype.replaceAll = function(search, replace) { //if replace is not sent, return original string otherwise it will //replace search string with ‘undefined’. if (replace === undefined) { return this.toString(); } return this.replace(new RegExp(‘[’ + search + ‘]’, ‘g’), replace); };

Please parse the string and then use javascript function.

str = str.replaceAll(‘abc’, ‘’); OR var expres= ‘abc’; str = str.replaceAll(expres, ‘’);

@Umanng Goel What if i need to replace the “ErrorCode” to “ResponseCode” and “1000” to “200”.

From:

{ “Status”: “PASSED”, “ErrorCode”: “1000”}

To:

{ “Status”: “PASSED”, “ResponseCode”: “200”}