Module:Json

From CrossCode Wiki
Jump to navigation Jump to search

Documentation for this module may be created at Module:Json/doc

-- <pre>
--------------------------------------------------------------------------------
-- A simple wrapper around @{mw.text.jsonEncode}.
--
-- @module  json
-- @release	stable
-- @author  [[User:ExE Boss]]
-- @require [[Module:Arguments]]
-- @see     @{mw.text.jsonEncode}
--------------------------------------------------------------------------------

local getArgs = require("Module:Arguments").getArgs;
local json = {};

local function tidyVal(key, val)
	if (type(val) == "string") then
		val = mw.text.unstripNoWiki(val);
		if (key ~= 1) then
			val = val:match("^%s*(.-)%s*$");
			if (val == "") then
				val = nil;
			end
		end
	end
	return val;
end

--------------------------------------------------------------------------------
-- Encodes a value to JSON, also supports invocation
--
-- @function json.encode
-- @param {Frame|table|string|number|boolean|nil} frame
-- @return {string}
--------------------------------------------------------------------------------
function json.encode(frame)
	local value = frame;
	if (
		type(frame) == "table"
		and type(frame.args) == "table"
		and type(frame.getParent) == "function"
	) then
		local args = getArgs(frame, {
			valueFunc = tidyVal,
		});
		value = args[1];

		local success, result = pcall(mw.text.jsonEncode, value);
		if (success) then
			return result;
		else
			return '<strong class="error">' .. result .. "</strong>";
		end
	else
		return mw.text.jsonEncode(value);
	end
end

return json;