With recent update we now allow trailing commas in JSON objects and arrays.

About a week ago the customer contacted us to help him to build JSON for his Call URL action. Based on two non-required text fields he needed to generate an array with zero, one or two elements.

It turned out to be a non-trivial task. Off two fields we have 4 possible combinations: empty array, one-element array with the content of Field 1, one-element array with the content of Field 2, and finally two-elements array with both Field 1 and Field 2. Something like:

<%? IsNull([Field 1]) and IsNull([Field 2])%> 
[]
<%?%>
<%? not IsNull([Field 1]) and IsNull([Field 2])%>
[ 
    <%=[Field 1]%> 
]
<%?%>
<%? IsNull([Field 1]) and not IsNull([Field 2])%>
[
    <%=[Field 2]%>
]
<%?%>
<%? not IsNull([Field 1]) and not IsNull([Field 2])%>
[
    <%=[Field 1]%>, 
    <%=[Field 2]%>
]
<%?%>

But is not four lines of formula a bit too much for two-elements array? Would not it better to write something like this?

[
    <%? not IsNull([Field 1])%><%=[Field 1]%>,<%?%>
    <%? not IsNull([Field 2])%><%=[Field 2]%><%?%>
]

As we have relatively strict JSON validation the code snippet above will produce an error. The problem is in comma separating two array elements. The code will successfully handle 3 of 4 cases (empty array; Field 2 only; Field 1 and Field 2), but absence of Field 2 generated output will end with dangling comma JSON standard does not allow. Perhaps this can be handled by adding extra conditions but with more optional elements in the array the complexity of the formula will grow exponentially.

So, we decided to do a little tweak. We now allow trailing commas in JSON arrays and objects. That is, we allow the comma after last array element or object’s property-value pair. And we remove them prior to sending the content to the server. With this addition latter snippet becomes valid.

Author
Date
Share