Handling API property that can be Array or Object
Argh! Dealing with an API that will return order lines as either an array of line objects when there are > 1 lines on the order or a single line object in the case of a single line order.
{
...
lines: [{
line_data...
}]
}
// OR
{
...
lines: {
line_data...
}
}
I'm setting up my Export transformation/mapping and trying to figure out if IIO has any clever notation to deal with this awkward situation? I tried basic array notation:
lines[*].line_data
Not surprisingly, for the single line format payload it results in no mapping.
To unblock myself I'll go ahead and homogenize the data in a preSavePage script but I'd still love to know if there's a native way to handle this scenario.
-
Steve,
Try setting up branching where one branch has the array, and the other does not.
This would also allow you to easily setup your mappings as you will have to configure the mappings to account for the array as well.
0 -
Thanks for the reply Kelly. I'm concerned about the maintenance load of duplicating the import and mappings. I was hoping for a way to transform the singular object into an array, then mappings can treat it generically.
I ended up doing this with a few lines of script in a pre Save Page script.
// We need to process the response from the API because if the order has 1 line,
// then SaleLines.SaleLine is an Object, if there are multiple lines, it's an Array.
// Totally stupid of the API designer, but whatever. We need to homogenize the
// response as Array so we can work with it in the rest of the flow.
options.data.forEach(sale => {
if (sale.sale_lines && Array.isArray(sale.sale_lines) === false) {
console.log('Wrapping single line Object in Array')
sale.sale_lines = [sale.sale_lines]
}
})I guess the feature request here is for transformation mapping to support array notation on source data and when it's a single object to still handle it. This would be very easy to support.
The above script could be replaced with a transformation mapping like:
record.sales_lines[*].fooBar ==> lines[*].fooBar
If sales_lines is an {} it would still handle it fine and map to an array with single record on the transformation result.
0 -
You can do this by adding both cases in the visual export transformation:
This works because if its an array only the top mapping will map, if its an object only the bottom one will be used.
I've used this before for an xml response that gets parsed to an object when there was only 1 entry. But yes it would be great if we could tell the parser what to always treat as an array.
0
Please sign in to leave a comment.
Comments
3 comments