Skip to content

Commit

Permalink
Add Json.stringifySubTables (#3345)
Browse files Browse the repository at this point in the history
* Add `Json.stringifySubTables`

* testcases for new function

* adjust comment
  • Loading branch information
hjpalpha authored Oct 12, 2023
1 parent e67e1fa commit 96f3e71
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
16 changes: 16 additions & 0 deletions standard/json.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
7 changes: 7 additions & 0 deletions standard/test/json_test.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 96f3e71

Please sign in to comment.