Pregunta

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.

¿Fue útil?

Solución

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

Otros consejos

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)()
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top