0

I want to initialise my array value like JSON data ,When i try its not initialising as properly,Here my code

My JSON value

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

I tried like the following

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

It not working,What change should i want to do further?

1 Answer 1

2

I assume you want to parse JSON data into a Lua table. If so, try this code:

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

2 Comments

@Fazil, try adding print(n,k,v) in the inner loop.
@Fazil works here! please be specific in your comments, "its not working" doesn't say what's wrong. If you run the code you will get a table of 5 subtables, each one having two keys, associated with the values shown in your JSON.

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.