Skip to content

Commit

Permalink
Add empty_table_as_array option for encode().
Browse files Browse the repository at this point in the history
  • Loading branch information
xpol committed May 17, 2017
1 parent e5fe470 commit ccd02f2
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
8 changes: 7 additions & 1 deletion spec/json_encode_spec.lua
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
require 'busted.runner'()


--luacheck: ignore describe it
describe('rapidjson.encode()', function()
local rapidjson = require('rapidjson')
Expand Down Expand Up @@ -127,8 +130,11 @@ describe('rapidjson.encode()', function()
)
end)

it('should support empty_table_as_array options', function()
assert.are.equal('{"a": []}', rapidjson.encode({a={}}, {empty_table_as_array=true}))
assert.are.equal('{"a": {}}', rapidjson.encode({a={}}))
end)
it('should support sort_keys and pretty options', function()

assert.are.equal(
[[{
"A": true,
Expand Down
6 changes: 4 additions & 2 deletions src/rapidjson.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -149,17 +149,19 @@ struct Key
class Encoder {
bool pretty;
bool sort_keys;
bool empty_table_as_array;
int max_depth;
static const int MAX_DEPTH_DEFAULT = 128;
public:
Encoder(lua_State*L, int opt) : pretty(false), sort_keys(false), max_depth(MAX_DEPTH_DEFAULT)
Encoder(lua_State*L, int opt) : pretty(false), sort_keys(false), empty_table_as_array(false), max_depth(MAX_DEPTH_DEFAULT)
{
if (lua_isnoneornil(L, opt))
return;
luaL_checktype(L, opt, LUA_TTABLE);

pretty = luax::optboolfield(L, opt, "pretty", false);
sort_keys = luax::optboolfield(L, opt, "sort_keys", false);
empty_table_as_array = luax::optboolfield(L, opt, "empty_table_as_array", false);
max_depth = luax::optintfield(L, opt, "max_depth", MAX_DEPTH_DEFAULT);
}

Expand Down Expand Up @@ -217,7 +219,7 @@ class Encoder {
luaL_error(L, "stack overflow");

lua_pushvalue(L, idx); // [table]
if (values::isarray(L, -1))
if (values::isarray(L, -1, empty_table_as_array))
{
encodeArray(L, writer, depth);
lua_pop(L, 1); // []
Expand Down
14 changes: 12 additions & 2 deletions src/values.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,22 @@ namespace values {
return has;
}

inline bool isarray(lua_State* L, int idx) {
inline bool isarray(lua_State* L, int idx, bool empty_table_as_array = false) {
bool arr = false;
if (hasJsonType(L, idx, arr)) // any table with a meta field __jsontype set to 'array' are arrays
return arr;

return luax::rawlen(L, idx) > 0; // any table has length > 0 are treat as array.
lua_pushvalue(L, idx);
lua_pushnil(L);
if (lua_next(L, -2) != 0) {
lua_pop(L, 3);

return luax::rawlen(L, idx) > 0; // any non empty table has length > 0 are treat as array.
}

lua_pop(L, 1);
// Now it comes empty table
return empty_table_as_array;
}


Expand Down

0 comments on commit ccd02f2

Please sign in to comment.