Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract all keys and values ​from a table

Tags:

lua

lua-table

I have a table that is the result of a json parser and I want to extract all the keys and values ​​from that table as well as the tables within it. How do I do that?

Example:

t = {
    a = {
        1,
        b = {2, 3},
        4,
    },
    c = {5, 6, 7}
}

result = extract(t) --result = a=(1, 4) b=(2, 3) c=(5, 6, 7)

like image 459
J. Igor Avatar asked Nov 23 '25 22:11

J. Igor


1 Answers

You can do it by traversing the table and collecting for each key an auxiliary array with all the values that are not tables. If a value is a table you repeat the process until you have traversed the whole tree.

t = {
   a = {
      1,
      b = {2, 3},
      4,
   },
   c = {5, 6, 7}
}

function rkeys(t, acc, name)
   local ret = {}
   for k, v in pairs(t) do
      if type(v) ~= 'table' then
         table.insert(ret, v)
      else
         rkeys(v, acc, k)
      end
   end
   if #ret > 0 then
      table.insert(acc, { [name] = ret })
   end
end

function extract(t)
   local ret = {}
   rkeys(t, ret)
   return ret
end

local result = extract(t)
for k,v in pairs(result) do
   for k1,v1 in pairs(v) do
      io.write(k1..": ") print("{"..table.concat(v1, ",").."}")
   end
end

Result:

b: {2,3}
a: {1,4}
c: {5,6,7}

Since the tree is traversed in-depth, the table values that are deeper in the table come first. If you'd like to get the results breadth first, you'd need to use an auxiliary list [1] (that will give you {a, c, b}).

[1] https://www.cs.bu.edu/teaching/c/tree/breadth-first/

like image 74
Diego Pino Avatar answered Nov 25 '25 16:11

Diego Pino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!