Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string into a table in Lua

Tags:

lua

lua-table

I am having a table data in string form. Sample is given below:

{"engName1":"HOLDER","validDurPeriod":3,"engName2":"INFORMATION","appStatus":2,"stayExpDate":"01/10/2012","engName3":"","appExpDate":"12/04/2010"}

How can I convert it into a proper table type variable so that I can access keys.I am new to lua and I am not aware if there is any existing method to do so.

like image 432
Vikram Singh Avatar asked Jun 21 '26 00:06

Vikram Singh


2 Answers

There is plenty of JSON parsers available for Lua, for example dkjson:

local json = require ("dkjson")

local str = [[
{
  "numbers": [ 2, 3, -20.23e+2, -4 ],
  "currency": "\u20AC"
}
]]

local obj, pos, err = json.decode (str, 1, nil)
if err then
  print ("Error:", err)
else
  print ("currency", obj.currency)
  for i = 1,#obj.numbers do
    print (i, obj.numbers[i])
  end
end

Output:

currency    €
1   2
2   3
3   -2023
4   -4
like image 170
Petr Abdulin Avatar answered Jun 23 '26 18:06

Petr Abdulin


Try this code to start with

J=[[
{"engName1":"HOLDER","validDurPeriod":3,"engName2":"INFORMATION","appStatus":2,"stayExpDate":"01/10/2012","engName3":"","appExpDate":"12/04/2010"}
]]
J=J:gsub("}",",}")
L={}
for k,v in J:gmatch('"(.-)":(.-),') do
    L[k]=v   
    print(k,v)
end

You'll still need to convert some values to number and remove quotes.

Alternatively, you can let Lua do the hard work, if you trust the source string. Just replace the loop by this:

J=J:gsub('(".-"):(.-),','[%1]=%2,\n')
L=loadstring("return "..J)()
like image 22
lhf Avatar answered Jun 23 '26 19:06

lhf



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!