From 96f3e71a69e3225c884a52831d0b15a2612f53c6 Mon Sep 17 00:00:00 2001 From: hjpalpha <75081997+hjpalpha@users.noreply.github.com> Date: Thu, 12 Oct 2023 19:36:50 +0200 Subject: [PATCH] Add `Json.stringifySubTables` (#3345) * Add `Json.stringifySubTables` * testcases for new function * adjust comment --- standard/json.lua | 16 ++++++++++++++++ standard/test/json_test.lua | 7 +++++++ 2 files changed, 23 insertions(+) diff --git a/standard/json.lua b/standard/json.lua index 0a54b60c5be..263e0e9e497 100644 --- a/standard/json.lua +++ b/standard/json.lua @@ -26,6 +26,22 @@ function Json.stringify(obj, pretty) return mw.text.jsonEncode(obj, pretty == true and mw.text.JSON_PRETTY or nil) end +---Json-stringifies subtables of a given table. +---@param obj table +---@param pretty boolean? +---@return table +function Json.stringifySubTables(obj, pretty) + local objectWithStringifiedSubtables = {} + for key, item in pairs(obj) do + if type(item) == 'table' then + objectWithStringifiedSubtables[key] = Json.stringify(item, pretty) + else + objectWithStringifiedSubtables[key] = item + end + end + + return objectWithStringifiedSubtables +end ---Parses a given JSON encoded table to its table representation. ---If the parse fails it returns an empty table. diff --git a/standard/test/json_test.lua b/standard/test/json_test.lua index 9d42cce73b4..b8cfbc14649 100644 --- a/standard/test/json_test.lua +++ b/standard/test/json_test.lua @@ -44,4 +44,11 @@ function suite:testParseIfTable() self:assertDeepEquals(nil, (Json.parseIfTable('banana'))) end +function suite:testStringifySubTables() + self:assertDeepEquals({}, Json.stringifySubTables{}) + self:assertDeepEquals({abc = 'def'}, Json.stringifySubTables{abc = 'def'}) + self:assertDeepEquals({abc = '["b","c"]'}, Json.stringifySubTables{abc = {'b', 'c'}}) + self:assertDeepEquals({a = '{"d":1,"b":"c"}', e = 'f'}, Json.stringifySubTables{a = {b = 'c', d = 1}, e = 'f'}) +end + return suite