使用JSON数据进行数组初始化 - lua

时间:2014-03-25 11:03:19

标签: arrays json lua

我想初始化我的数组值,如JSON数据,当我尝试不正确初始化时,在这里我的代码

我的JSON值

 [{"ShiftCode":"1","ShiftName":"BREAKFAST"},
 {"ShiftCode":"2","ShiftName":"LUNCH"}, 
 {"ShiftCode":"2","ShiftName":"LUNCH"},
 {"ShiftCode":"3","ShiftName":"DINNER"},
 {"ShiftCode":"3","ShiftName":"DINNER"}] 

我尝试了以下

 shiftArr={'[[[{"ShiftCode":"1","ShiftName":"BREAKFAST"},{"ShiftCode":"2","ShiftName":"LUNCH"},{"ShiftCode":"2","ShiftName":"LUNCH"},{"ShiftCode":"3","ShiftName":"DINNER"},{"ShiftCode":"3","ShiftName":"DINNER"}]]]'};

它不起作用,我想进一步做些什么改变?

1 个答案:

答案 0 :(得分:2)

我假设您要将JSON数据解析为Lua表。如果是这样,请尝试以下代码:

J=[[
[{"ShiftCode":"1","ShiftName":"BREAKFAST"},
 {"ShiftCode":"2","ShiftName":"LUNCH"}, 
 {"ShiftCode":"2","ShiftName":"LUNCH"},
 {"ShiftCode":"3","ShiftName":"DINNER"},
 {"ShiftCode":"3","ShiftName":"DINNER"}] 
]]

L={}
n=0
for t in J:gmatch("%b{}") do
    n=n+1
    L[n]={}
    for k,v in t:gmatch('"(.-)":"(.-)"') do
        L[n][k]=v   
    end
end