Module:NiceJSON

From Parallel Wiki
Revision as of 12:02, 6 October 2023 by minecraft>MarkusRost
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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

local p = {}

-- encodes the input into JSON
p.stringify_raw = function(x)
	local js = mw.text.jsonEncode(x, mw.text.JSON_PRETTY)
	js = js:gsub('\r?\n', ' ')
	js = js:gsub('  +', ' ')
	js = mw.text.nowiki(js)
	return js
end
-- encodes input into JSON; returns empty string on error
p.stringify = function(data)
	local ok, json = pcall(p.stringify_raw, data)
	if ok then
		return json
	else
		return ''
	end
end
-- encodes input into JSON and wraps it in the provides tag with class
-- if no_empty is truthy, returns just an empty string on error; if falsey returns the tag (which has no contents)
p.wrap = function (data, tag, class, no_empty)
	local js = p.stringify(data)
	if js == '' and no_empty then
		return ''
	end
	return string.format('<%s class="%s noexcerpt navigation-not-searchable">%s</%s>', tag, class, js, tag)
end
return p