How can I unescape characters in Javascript?

So I have the following values in my flow variable

{"Accounts":"[{\"AccountId\":\"ABC123\",\"MaskedAccountNumber\":\"***123\"}]"}

And I want to throw this to the backend/endpoint I'm calling unescaped. How do I do that in apigees JS Policy / JS File?.

I already tried using

var decoded= unescape(variable_name);

and

var decoded = decodeURI(variable_name);

And, they just don't work. 😕

Here is my JS code

  var link_accounts ={
    "Accounts" : context.getVariable(decodeURIComponent("accesstoken.Accounts")) ,
      "BillerCode": context.getVariable("accesstoken.BillerCode") ,
      "UserAccessToken": context.getVariable("accesstoken.UserAccessToken") ,
      "access_token": context.getVariable("apigee.access_token") ,
      "refresh_token" : context.getVariable("refresh_token")
} 
context.setVariable("link_accounts",JSON.stringify(link_accounts));




Solved Solved
1 2 303
1 ACCEPTED SOLUTION

I think what you want is JSON.parse()

var link_accounts = {
    Accounts        : JSON.parse(context.getVariable("accesstoken.Accounts")) ,
    BillerCode      : context.getVariable("accesstoken.BillerCode") ,
    UserAccessToken : context.getVariable("accesstoken.UserAccessToken") ,
    access_token    : context.getVariable("apigee.access_token") ,
    refresh_token   : context.getVariable("refresh_token")
}; 
context.setVariable("link_accounts",JSON.stringify(link_accounts));

Also, you don't need to quote the property names when setting the var link_accounts. The JSON.stringify() will do that for you, later.

View solution in original post

2 REPLIES 2

I think what you want is JSON.parse()

var link_accounts = {
    Accounts        : JSON.parse(context.getVariable("accesstoken.Accounts")) ,
    BillerCode      : context.getVariable("accesstoken.BillerCode") ,
    UserAccessToken : context.getVariable("accesstoken.UserAccessToken") ,
    access_token    : context.getVariable("apigee.access_token") ,
    refresh_token   : context.getVariable("refresh_token")
}; 
context.setVariable("link_accounts",JSON.stringify(link_accounts));

Also, you don't need to quote the property names when setting the var link_accounts. The JSON.stringify() will do that for you, later.

Woah, I missed that JSON.parse function. Great. It's now working.

Thanks for the note too @Dino-at-Google . Greatly appreciated as I barely code in JS and that's good to know. ^_^. ♥