Module:Graph:Utils

local p = {}

function p.titleToJson(title) -- Load mediawiki page and decodes it as json local t = mw.title.new(title) if not t.exists then return nil else return mw.text.jsonDecode(t:getContent, mw.text.JSON_TRY_FIXING) end end

function p.recodeListToMap(frame) -- a function to re-code a json table in format [{},{},{}] to a map {}, -- with each source object containing the same set of values, and the response -- mapping the "from" value to "to" value -- parameters: tbl, from, to	local args = frame.args local tbl = p.titleToJson(args[1]) local from = args[2] local to = args[3] local result = p.recodeListToMapFunc(tbl, from, to, args) return mw.text.jsonEncode(result) end function p.recodeListToMapFunc(tbl, from, to, values) -- a function to re-code a json table in format [{},{},{}] to a map {}, -- with each source object containing the same set of values, and the response -- mapping the "from" values to "to" values -- parameters: tbl, from, to	local dict = {} for k, v in pairs(tbl) do		if v[from] ~= nil and v[to] ~= nil then dict[v[from]] = v[to] end end local result = {} for key, val in pairs(values) do		if type(key) == "string" then local k = dict[key] if k ~= nil then result[k] = val end end end return result end

function p.parseCsv(frame) local content = mw.title.new(frame.args[1]):getContent local result = p.parseCsvFunc(content) return mw.text.jsonEncode(result) end

function p.parseCsvFunc(content) -- Simple, no escaping, csv parser. Assumes first row contains columns local result = {} local headers = false

for v in string.gmatch(content, '([^\n]*)') do		local val = mw.text.trim(v) if val ~= '' then local parts = mw.text.split( val, ',', true ) if headers == false then -- set headers (trimmed) headers = {} for i, v in ipairs(parts) do					table.insert(headers, mw.text.trim(v)) end else local row = {} for i, v in ipairs(parts) do					row[headers[i]] = mw.text.trim(v) end table.insert(result, row) end end end return result end

return p