3

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.

1

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

is this applicable on mobile platforms also. Because I am working on Kony framework for J2ME devices using lua as language..and when I tried to put this file, it is not even letting me start my app..also i tried with different json parser, then it is unable to identify keyword "require"...
@Vikram I'm not sure about that, require is a built-in function lua.org/pil/8.1.html so generally it should be there..
1

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)()

11 Comments

do I have to add those square brackets into string for this operation.?? Please ask if something is not clear from my side..
@Vikram Yes. The square brackets will tell lua that the item inside it is a key.
@Vikram, for the sample data you gave, you don't need to add square brackets around keys. I just wanted to make the code a little more robust, in case keys had spaces in them.
@lhf: I am trying with your second approach and it is crashing at "J=J:gsub('(".-"):(.-),','[%1]=%2,\n')". I have added brackets at both ends. Is this a generic code or only given sample specific, because my actual string is having a collection as a value of one of keys.
The last component of J is not terminated with ,, so it will not be processed in the second solution.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.