Module:FilterJsonById

From AoP Wiki
Revision as of 14:20, 18 February 2025 by Zmeja (talk | contribs) (Added FilterJsonById Module)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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

local http = require('mw.http')
local json = require('cjson')

local p = {}

function p.filterById(frame)
    -- Fetch the JSON data from the URL
    local url = frame.args.url
    local response = http.get(url)

    -- If there's a response
    if response then
        -- Decode the JSON response into a Lua table
        local data = json.decode(response)

        -- Retrieve the ID passed to the module
        local targetId = frame.args.id

        -- Table to hold the filtered results
        local filteredData = {}

        -- Loop through the entries in the JSON
        for _, entry in ipairs(data) do
            -- Check if the 'id' matches the target ID
            if entry.ProtoId == targetId then
                table.insert(filteredData, entry)
            end
        end

        -- If we found matching entries, format the result
        if #filteredData > 0 then
            local result = ""
            for _, entry in ipairs(filteredData) do
                result = result .. "<div>Entry ID: " .. entry.id .. "</div>"
                result = result .. "<div>Name: " .. entry.name .. "</div>"
                -- Add other fields as needed
            end
            return result
        else
            return "No entries found with the specified ID."
        end
    else
        return "Error: Could not fetch data."
    end
end

return p