Storing arrays in Node API

Enonic version: 6.12.0
OS: Windows

Hi! I am working on my forms-app (a bit unsure if it will be ready to submit to the Market by Christmas, but probably by the end of January at least), and ran into a problem like this one:
https://discuss-3.enonic.com/t/item-sets-vary-between-returning-an-object-and-an-array/190

Basically, I store an object like this in the node API:
{ 'id': 'my-id', 'title': 'My title', 'fields': [ { 'id': 'id', 'label': 'Label' } ] }

In short, an object with a property that is an array. This can be empty, have one object or have multiple objects in it, but I always store it as an array. However, when I retrieve this object (or inspect it in RepoXPlorer), the array (if stored with one object in it) will be stored as an object instead. If the array is empty, it will not even be stored.

Is this intentional? I (kind of) get it with ItemSets and other components you use in the official apis, but I thought we had full control of our data in the node API. I know I can use the lib-util forceArray function, but I really don’t want to mess up my code if I don’t have to…

Is it possible this is an unintended side-effect of your decision to handle arrays in ItemSets?

Any thoughts on this?

Hi Vegard.

I understand why this might seem strange at frist, however all aspects of the API mappings to JSON/node API are intentional.

Basically the designs relate to how the underlying Java Node API works, and how this naturally maps to Javascript/JSON. In the Java API there is no such thing as an array, you simply add new values into the document tree structure without dealing with arrays. We actually don’t have information in the core node API that somethign is an array with only one value inside it, we only know the number of items. Remember that this is also a schema-less approach, so there is no schema either that tells us this property should be an array.

So, this is a tradeoff where you don’t deal with arrays (in Java), and also the JSON result from the Node API will be consistent and clean to read (vs having arrays for every single property). It always has the values if there is one value, arrays if there are multipe, and null if the value was empty. The only “exception” is empty string, which is considered a value and not “null”.

The fact that your sample JSON above actually works is supported by convenience, it is not correct node syntax. The alternative would be to throw an error instead.

When coding with javascript we always recommend using the util library as this completely abstracts these issues anyway: https://github.com/enonic/lib-util/tree/master/src/main/resources/site/lib/enonic/util

2 Likes