Module:Data to Table: Difference between revisions
ReisuDesign (talk | contribs) No edit summary |
ReisuDesign (talk | contribs) No edit summary |
||
| Line 14: | Line 14: | ||
-- Escape characters | -- Escape characters for Lua strings | ||
local function clean(txt) | local function clean(txt) | ||
return txt | return txt | ||
| Line 60: | Line 60: | ||
local sortkey = frame.args.sortkey or 'page' | local sortkey = frame.args.sortkey or 'page' | ||
local subtable = frame.args.subtable | local subtable = frame.args.subtable | ||
-- JSON mode | |||
local jsonMode = tostring(frame.args.json) == '1' | |||
-- Constant value mode | -- Constant value mode | ||
| Line 87: | Line 90: | ||
end | end | ||
-- ============================================================ | |||
-- JSON OUTPUT | |||
-- ============================================================ | |||
if jsonMode then | |||
local jsonEntries = {} | |||
-- Sort entries using the same sorting logic as normal output | |||
local sortedEntries = {} | |||
for _, entry in lib.spairs( | |||
info, | |||
function(tVal, a, b) | |||
if sortkey == 'INPUT' then | |||
return a < b | |||
else | |||
return (tVal[a][sortkey] or '') < (tVal[b][sortkey] or '') | |||
end | |||
end | |||
) do | |||
if ne(entry.page) then | |||
jsonEntries[#jsonEntries + 1] = entry.page | |||
end | |||
end | |||
-- Encode the array as valid JSON | |||
local jsonText = mw.text.jsonEncode(jsonEntries) | |||
local output = frame:extensionTag( | |||
'syntaxhighlight', | |||
jsonText, | |||
{ | |||
lang = 'json', | |||
copy = '' | |||
} | |||
) | |||
-- Copy button | |||
if frame.args.copy then | |||
output = require('Module:CopyText')._main({ | |||
output, | |||
frame.args.copy, | |||
'Copy JSON' | |||
}) | |||
end | |||
return output | |||
end | |||
-- ============================================================ | |||
-- LUA OUTPUT | |||
-- ============================================================ | |||
-- Build result | -- Build result | ||
| Line 237: | Line 294: | ||
-- | -- ================================================================ | ||
-- FORMAT DATA | |||
-- ================================================================ | |||
function p.BuildEntry(value, key, level, subtable, unquoted) | function p.BuildEntry(value, key, level, subtable, unquoted) | ||
level = level or 1 | level = level or 1 | ||
| Line 265: | Line 325: | ||
value = '{ \'' .. | value = '{ \'' .. | ||
table.concat(value, '\', \'') .. | table.concat(value, '\', \'') .. | ||
' }' | ' }' | ||
| Line 320: | Line 380: | ||
' = ', | ' = ', | ||
value, | value, | ||
',' | ',' | ||
) | ) | ||
| Line 331: | Line 391: | ||
-- | -- ================================================================ | ||
-- PARSE DATA KEYS INTO SPECIFIED LEVELS | |||
-- ================================================================ | |||
function p.ParseKeys(keys) | function p.ParseKeys(keys) | ||
keys = lib.split(keys, ';;') | keys = lib.split(keys, ';;') | ||