Skip to content

Instantly share code, notes, and snippets.

@davidbirdsong
Created May 15, 2013 22:40
Show Gist options
  • Save davidbirdsong/5588008 to your computer and use it in GitHub Desktop.
Save davidbirdsong/5588008 to your computer and use it in GitHub Desktop.
cjson, lua and empty tables

this is an annoying side effect of lua tables consider the following:

an empty table when encoded returns a map-like json structure

[david@foulplay ~]$ lua
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> require('cjson')
> t= {}
> return cjson.encode(t)
{}

try to trick it by do a list-like operation table.insert on the table with a nil value which doesn't work. we still get a map-like json output

> table.insert(t, nil)
> return cjson.encode(t)
{}

if we insert an integer value we get a list back in json

> table.insert(t, 1)
> return cjson.encode(t)
[1]

...and now for the really annoying illustration: we mix list and map features into our table and json spits out our list as if it was a map all along.

> t['foo'] = 'bar'
> return cjson.encode(t)
{"1":1,"foo":"bar"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment