From fd7a1af7ffec4be04348b4807a4a8f95777e2515 Mon Sep 17 00:00:00 2001 From: Stefan Ursella Date: Fri, 26 Apr 2024 07:26:52 +0200 Subject: [PATCH] lua: json: add method to merge json containers --- modules/module-lua-scripting/api/json.c | 15 +++++++++++++++ tests/wplua/scripts/json.lua | 23 +++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/modules/module-lua-scripting/api/json.c b/modules/module-lua-scripting/api/json.c index 39f6b10f0..242f0e410 100644 --- a/modules/module-lua-scripting/api/json.c +++ b/modules/module-lua-scripting/api/json.c @@ -167,6 +167,20 @@ push_luajson (lua_State *L, WpSpaJson *json, gint n_recursions) } } +static int +spa_json_merge (lua_State *L) +{ + WpSpaJson *a = wplua_checkboxed (L, 1, WP_TYPE_SPA_JSON); + WpSpaJson *b = wplua_checkboxed (L, 2, WP_TYPE_SPA_JSON); + + WpSpaJson *merge = wp_json_utils_merge_containers(a, b); + if(!merge) + luaL_error (L, "only Json container merge supported"); + + wplua_pushboxed (L, WP_TYPE_SPA_JSON, merge); + return 1; +} + static int spa_json_parse (lua_State *L) { @@ -340,6 +354,7 @@ static const luaL_Reg spa_json_methods[] = { { "is_array", spa_json_is_array }, { "is_object", spa_json_is_object }, { "parse", spa_json_parse }, + { "merge", spa_json_merge }, { NULL, NULL } }; diff --git a/tests/wplua/scripts/json.lua b/tests/wplua/scripts/json.lua index 52a8a3823..03e14ba6d 100644 --- a/tests/wplua/scripts/json.lua +++ b/tests/wplua/scripts/json.lua @@ -240,3 +240,26 @@ assert (type (val.args) == "table") assert (type (val.args.test) == "table") assert (val.args.test[1] == 0) assert (val.args.test[2] == 1) + +json = Json.Array { "foo" } +json2 = Json.Array { "bar" } +json = json:merge(json2) +assert (json:is_array()) +val = json:parse () +assert (val[1] == "foo") +assert (val[2] == "bar") + +table = {} +table["1"] = 1 +table["2"] = 2 +json = Json.Object (table) +table = {} +table["3"] = 3 +table["4"] = 4 +json2 = Json.Object (table) +json = json:merge(json2) +val = json:parse () +assert (val["1"] == 1) +assert (val["2"] == 2) +assert (val["3"] == 3) +assert (val["4"] == 4) -- GitLab