Module:GetJSON/2

From AlternateWiki

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

local p = {}

function p.splitKey(key)
    return mw.text.split(key, '%.')
end

function p.getValue(data, key)
    local segments = p.splitKey(key)
    local value = data
    for _, segment in ipairs(segments) do
        local index = tonumber(string.match(segment, '#(%d+)'))
        if index then
            if type(value) == 'table' then
                local count = 0
                for k, v in pairs(value) do
                    count = count + 1
                    if count == index then
                        value = v
                        break
                    end
                end
            else
                return nil
            end
        else
            value = value[segment]
        end
        if not value then
            return nil
        end
    end
    return value
end

function p.formatValue(value, valueType)
    if valueType == 'length' then
        if type(value) == 'table' then
            return tostring(#value)
        elseif type(value) == 'string' then
            return tostring(value:len())
        else
            return nil
        end
    elseif type(value) == 'table' then
        if valueType == 'keys' then
            return table.concat(p.getKeys(value), ';')
        else
            return table.concat(value, ';')
        end
    else
        return tostring(value)
    end
end

function p.getKeys(tbl)
    local keys = {}
    for k, _ in pairs(tbl) do
        table.insert(keys, k)
    end
    return keys
end

function p.main(frame)
    local args = frame.args
    local jsonPage = args[1]
    local key = args[2]
    local fallback = args[3]
    local valueType = args[4]

    local jsonData = mw.ext.data.getJson(jsonPage)

    if not jsonData then
        return fallback
    end

    local value = p.getValue(jsonData, key)

    if not value then
        return fallback
    end

    return p.formatValue(value, valueType)
end

return p