" (double quotes) are _usually_ a problem within a String that must be enclosed by "'s.
Now, pretend you need to construct a JSON string in a UCCX/IP IVR AEF script - which needs you to use double quotes around Strings - but it also has to be dynamic: there must be a way to add values that may come from an external source.
String concatenation is sooo 80's and ugly anti pattern and not elegant.
Let's implement String interpolation instead - with templates. It's simple, it's reusable and easy to test.
Of course, the UCCX scripting toolbox has got everything we need:
- the u prefix* which allows escaping double qoutes using \" (without this prefix it just won't accept \") and
- the String.format( String template, Object[] arguments ) static method.
First, the template:
String template = u"{\"fruit\":\"%1s\"}"
This just translates to a simple JSON object, a Map or a list of key-value pairs if you insist, with a one key: fruit.
%1s is placeholder, meaning "take the first argument and format it as a String". In this example, template is just a UCCX String variable:
Pretend, at some point we collect the value we need in order to construct our JSON string. Perhaps from a database. This value is stored in a String variable externalValue. In this example, externalValue = "banana".
Let's put template and externalValue together in order to create the value of completeJsonString.
Set completeJsonString = String.format(template, new Object[] {externalValue} )
What just happened?
String.format is an elegant, yet underrated Java method. UCCX scripting is Java scripting, but instead of varargs it uses an array of objects.
The first argument is the template. The template value has a placeholder. Placeholders start with the percent sign, followed by the position (1, 2, n) and a format - in our case, s is just an instruction to pass it along (~ format the incoming String as a String).
Format what: the second argument's values. This needs to be an array of Objects (Object[]) which we construct and initialize on the fly, this is why new Object[] { externalValue }.
Let's test it (easiest: by using the debug methods available in CCX Editor):
And hey presto, we receive a nice JSON string: U"{\"fruit\":\"banana\"}" which is of course {"fruit":"banana"}.
* Thanks @dmacias for the tip with the u prefix.