[pshaiCmd] JSON to Table

stable
By pshai in Other Published March 2020 👁 1,741 views 💬 0 comments

Description

Converts a JSON object/data string to a table/array.
HaasScript
DefineCommand('JsonToTable', 'Converts JSON string/object to a table')

local input = DefineParameter(DynamicType, 'input', 'JSON string or object', true, '', 'Text, Input, ParseJson')
local jsonToTable

jsonToTable = function(input, isCell)
    if isCell == nil then isCell = false end
    local ret = {}
    local i = 1

    for _,v in pairs(input) do
        local t = GetType(v)

        if t == ArrayDataType
        or t == UserDataDataType
        then
            ret[i] = jsonToTable(v, true)
        else
            ret[i] = v
        end

        i = i + 1
    end

    local ret2 = {}
    if not isCell and ret[1] != nil then
        for i=1, #ret[1] do
            ret2[i] = ret[1][i]
        end
    end

    return isCell and ret or ret2
end

local ret = {}

if input != nil then
    if GetType(input) == UserDataDataType then
        ret = jsonToTable(input)
    elseif GetType(input) == TextDataType and #input > 0 then
        ret = jsonToTable(ParseJson(input))
    end
end

DefineOutput(ListDynamicType, ret, 'Table containing values from JSON')

0 Comments

Sign in to leave a comment.

No comments yet. Be the first!