Skip to content

Commit 1bd086a

Browse files
committed
Allow differentiation of arrays and objects for proper empty-object serialization
detail see : mpx#11
1 parent d8cd9d9 commit 1bd086a

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

lua_cjson.c

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -505,9 +505,25 @@ static int lua_array_length(lua_State *l, json_config_t *cfg, strbuf_t *json)
505505
int max;
506506
int items;
507507

508-
max = 0;
508+
max = -1;
509509
items = 0;
510510

511+
if ( lua_getmetatable(l, -1) ) {
512+
int is_array, has_is_array;
513+
514+
lua_pushliteral(l, "__is_cjson_array");
515+
lua_rawget(l, -2);
516+
has_is_array = lua_isboolean(l, -1);
517+
is_array = has_is_array && lua_toboolean(l, -1);
518+
lua_pop(l, 2);
519+
520+
if ( has_is_array && ! is_array ) {
521+
return -1;
522+
} else {
523+
max = 0;
524+
}
525+
}
526+
511527
lua_pushnil(l);
512528
/* table, startkey */
513529
while (lua_next(l, -2) != 0) {
@@ -696,7 +712,8 @@ static void json_append_data(lua_State *l, json_config_t *cfg,
696712
current_depth++;
697713
json_check_encode_depth(l, cfg, current_depth, json);
698714
len = lua_array_length(l, cfg, json);
699-
if (len > 0 || (len == 0 && !cfg->encode_empty_table_as_object))
715+
/** if (len >= 0 || !cfg->encode_empty_table_as_object) **/
716+
if (len >= 0)
700717
json_append_array(l, cfg, current_depth, json, len);
701718
else
702719
json_append_object(l, cfg, current_depth, json);
@@ -1215,6 +1232,16 @@ static void json_parse_array_context(lua_State *l, json_parse_t *json)
12151232

12161233
/* Handle empty arrays */
12171234
if (token.type == T_ARR_END) {
1235+
// Mark as array:
1236+
luaL_getmetatable(l, "cjson.array");
1237+
if ( lua_isnil(l, -1) ) {
1238+
lua_pop(l, 1);
1239+
luaL_newmetatable(l, "cjson.array");
1240+
lua_pushboolean(l, 1);
1241+
lua_setfield(l, -2, "__is_cjson_array");
1242+
}
1243+
lua_setmetatable(l, -2);
1244+
12181245
json_decode_ascend(json);
12191246
return;
12201247
}

0 commit comments

Comments
 (0)