Skip to content

option to force to encode empty table to "[]" #25

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions lua_cjson.c
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@
#define DEFAULT_DECODE_INVALID_NUMBERS 0
#endif

#define MT_AS_ARRAY "MT_AS_ARRAY"

typedef enum {
T_OBJ_BEGIN,
T_OBJ_END,
Expand Down Expand Up @@ -687,8 +689,22 @@ static void json_append_data(lua_State *l, json_config_t *cfg,
len = lua_array_length(l, cfg, json);
if (len > 0)
json_append_array(l, cfg, current_depth, json, len);
else
json_append_object(l, cfg, current_depth, json);
else {
int is_array = 0;
int got = lua_getmetatable(l, -1);
if (got > 0) {
luaL_getmetatable(l, MT_AS_ARRAY);
is_array = lua_rawequal(l, -1, -2);
lua_pop(l, 2);
}

if (is_array) {
json_append_array(l, cfg, current_depth, json, 0);
}
else {
json_append_object(l, cfg, current_depth, json);
}
}
break;
case LUA_TNIL:
strbuf_append_mem(json, "null", 4);
Expand Down Expand Up @@ -1377,6 +1393,9 @@ static int lua_cjson_new(lua_State *l)
lua_pushlightuserdata(l, NULL);
lua_setfield(l, -2, "null");

luaL_newmetatable(l, MT_AS_ARRAY);
lua_setfield(l, -2, "as_array");

/* Set module name / version fields */
lua_pushliteral(l, CJSON_MODNAME);
lua_setfield(l, -2, "_NAME");
Expand Down
7 changes: 7 additions & 0 deletions tests/test.lua
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ local NaN = math.huge * 0;

local testdata = load_testdata()

local empty_array = {}
setmetatable(empty_array, json.as_array)

local cjson_tests = {
-- Test API variables
{ "Check module name, version",
Expand Down Expand Up @@ -212,6 +215,10 @@ local cjson_tests = {
json.encode, { 10 }, true, { '10' } },
{ "Encode string",
json.encode, { "hello" }, true, { '"hello"' } },
{ "Encode empty table as array",
json.encode, { empty_array }, true, { '[]' } },
{ "Encode empty table as table",
json.encode, { {} }, true, { '{}' } },
{ "Encode Lua function [throw error]",
json.encode, { function () end },
false, { "Cannot serialise function: type not supported" } },
Expand Down