@@ -505,9 +505,25 @@ static int lua_array_length(lua_State *l, json_config_t *cfg, strbuf_t *json)
505
505
int max ;
506
506
int items ;
507
507
508
- max = 0 ;
508
+ max = -1 ;
509
509
items = 0 ;
510
510
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
+
511
527
lua_pushnil (l );
512
528
/* table, startkey */
513
529
while (lua_next (l , -2 ) != 0 ) {
@@ -696,7 +712,8 @@ static void json_append_data(lua_State *l, json_config_t *cfg,
696
712
current_depth ++ ;
697
713
json_check_encode_depth (l , cfg , current_depth , json );
698
714
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 )
700
717
json_append_array (l , cfg , current_depth , json , len );
701
718
else
702
719
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)
1215
1232
1216
1233
/* Handle empty arrays */
1217
1234
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
+
1218
1245
json_decode_ascend (json );
1219
1246
return ;
1220
1247
}
0 commit comments