Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: encoding empty array #1

Closed
bjne opened this issue Mar 21, 2014 · 3 comments
Closed

feature: encoding empty array #1

bjne opened this issue Mar 21, 2014 · 3 comments

Comments

@bjne
Copy link

bjne commented Mar 21, 2014

Would be nice to be able to set a flag to force a empty table to be
encoded as an array []

Also mentioned here: mpx/lua-cjson#11
and here: http://openmymind.net/Lua-JSON-turns-empty-arrays-into-empty-hashes/

@bungle bungle closed this as completed in d5dd274 Mar 25, 2014
@bungle
Copy link
Owner

bungle commented Mar 25, 2014

Okay, I think I have fixed this now. Example code:

local json = require "cjson"
print(json.decode("[]").__jsontype) -- "array"

-- you could also check it like this:
print(getmetatable(json.decode("[]")) == json.object) -- false
print(getmetatable(json.decode("[]")) == json.array) -- true
-- or
print(json.decode("[]").__jsontype == "object") -- false
print(json.decode("[]").__jsontype == "array") -- true

print(json.decode("{}").__jsontype) -- "object"
print(json.encode(setmetatable(json.decode("[]"), json.object))) -- {}
print(json.encode(setmetatable(json.decode("{}"), json.array))) -- []
print(json.encode(json.decode("[]"))) -- []
print(json.encode(json.decode("{}"))) -- {}

Was this what you were looking for?

json.encode({}) returns [], but json.encode(setmetatable({}, json.object)) returns {}. And json.encode({ a = "b" }) returns { "a": "b" }. Also json.encode(setmetatable({ a = "b" }, json.array)) returns { "a": "b" } (I'm not sure though, is the last example "right", should it forcefully throw away all the keys instead, and return just []?).

And you are welcomed to reopen this issue, if you feel like it was not resolved.

Regards
Aapo

@goecho
Copy link

goecho commented Aug 1, 2014

good works.

@apristen
Copy link

thanks!
in which version it is fixed?
I have lua-cjson-2.1.0.4 and cjson.encode(cjson.decode("[[],{}]")) returns me [{},{}]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants