Module:Lua json

From Visual Data Wiki
Jump to navigation Jump to search

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

local p = require('Module:Http')
local json = require('Module:Json')

local function queryPages(titleParam, titleValue)
    local url = mw.uri.fullUrl('api.php', {action = 'query', format = 'json', list = 'allpages', apnamespace = 486})
    local response = p.get(url)
    local data = json.decode(response)

    if not data or not data.query or not data.query.allpages then
        return {}
    end

    local pages = {}
    for _, page in ipairs(data.query.allpages) do
        table.insert(pages, page.title)
    end

    return pages
end

function p.getDataByTitle(titleParam, titleValue, targetParam)
    local pages = queryPages(titleParam, titleValue)
    local results = {}

    for _, pageTitle in ipairs(pages) do
        local jsonPage = mw.title.new(pageTitle)
        if jsonPage and jsonPage.exists and jsonPage.contentModel == 'json' then
            local content = jsonPage:getContent()
            local jsonData = json.decode(content)
            if jsonData and jsonData[titleParam] == titleValue then
                table.insert(results, jsonData[targetParam])
            end
        end
    end

    return results
end

return p