Lua's JSON turns empty arrays into empty hashes

May 07, 2013

We recently ran into an issue that took us a while to figure out. Basically, a return value would go from being an empty array:

  genres: []

To an empty hash:

  genres: {}

Not good. Worse, we couldn't figure it out...it was sporadic...impossible. How could an empty array turn into an empty hash?!

Or...Lua uses tables to represent both arrays and dictionaries, so how can it possibly differentiate? From the docs:

Lua CJSON uses a heuristic to determine whether to encode a Lua table as a JSON array or an object. A Lua table with only positive integer keys of type number will be encoded as a JSON array. All other tables will be encoded as a JSON object.

For us, this meant moving the decoding/encoding out of LUA and passing in the values. Since this is easy to overlook, I hope it saves someone