xpol/lua-rapidjson

Adding data to decoded empty table produce no change when encode again

brynne8 opened this issue · 8 comments

Version: Lua 5.1 on Windows x86
Steps to reproduce: Run the following program

local json = require('rapidjson')

local a = {}

local str = json.encode(a)
a = json.decode(str)
print(json.encode(a))

a[1] = 'def'

print(json.encode(a))

Output

{}
{}

Expected output

{}
["def"]
xpol commented

Because the a deocded from str has metatable {__jsontype= 'object'}. This tells lua rapdijson that the table should always tread as json object.

> json = require('rapidjson')
> a = {}
> str = json.encode(a)
> a = json.decode(str)
> t = getmetatable(a)
> t.__jsontype
object
> 

@xpol So why didn't rapidjson handle this? How can I re-encode it as JSON string? The cjson module handles the case as well, as produced expected output. As in Lua, there's no difference between array and object, both treated as tables.

I mean, why not simply remove the metatable __jsontype before passing to Lua? It will be more convenient, and will still auto detect it is an object or array.

xpol commented

Modify your code.

local a = {}

to

local a = rapidjson.array()

the a will be always be treated as array.

But still, this would lose generality, to switch from libraries... Well thanks.

xpol commented

Did you mean got a JSON empty object decoded into a Lua table and you want
later encode it as array?

Yes! That's it. If could be so. Maybe it's because I used JSON as a serialization method, and I just want it could be encoded and decoded back and forth, and able to re-encode, if, my Lua table is already changed, as I suggest, from object to array, or vice versa.

xpol commented