-- John Longworth June 2017 -- JSON stands for JavaScript Object Notation -- sjson module needs to be in your build posn = "{\"lon\":-2.47,\"lat\":53.67}" t = sjson.decode(posn) for k,v in pairs(t) do print(tostring(k),v) end print("Longitude = "..t.lon) print("Latitude = "..t.lat) print("\n") ------------------------------------- json = [[{"SensorType":"DHT11","Temperature":18,"Humidity": 73}]] for k,v in pairs(sjson.decode(json)) do print(k,v) end print("\n") ------------------------------------- local decoder = sjson.decoder() decoder:write("[10, 1") decoder:write("2") decoder:write(", \"foo\"]") print(decoder:result()) for k,v in pairs(decoder:result()) do print (k, v) end print("\n") ------------------------------------- ok, json = pcall(sjson.encode, {key="value",sensor=7,job="Waiter"}) if ok then print(json) else print("failed to encode!") end for k,v in pairs(sjson.decode(json)) do print(string.format("%7s %8s",k,v)) end print("\n") ------------------------------------- wnd = '{"window": {"title": "Sample Widget","name": "main_window","width": 500, "height": 600}}' t = sjson.decode(wnd) for k,v in pairs(t.window) do print(k,v) end print("\nTitle : ",t.window.title) print("Name : ",t.window.name) print("Width : ",t.window.width) print("Height : ",t.window.height.."\n") --------------------------------------- myObj = '{"name":"Mark","age":31,"city":"New York"}' t = sjson.decode(myObj) for k,v in pairs(t) do print(k,v) end print("\nName :",t.name) print("Age :",t.age) print("City :",t.city.."\n") --------------------------------------- ok, json = pcall(sjson.encode, {key=4,age=35,name="Fred"}) if ok then print(json) t = sjson.decode(json) for k,v in pairs(t) do print(string.format("%5s %1s ",k,v)) end print("\n") else print("failed to encode!") end --------------------------------------- -- Array types----- emps = '{"employees":["Mary","John", "Anna", "Paul"]}' t = sjson.decode(emps) for k,v in pairs(t.employees) do print(k,v) end print(t.employees[1].."\n") --------------------------------------- forecast = '{"weather":[{"main":"Clouds","description":"broken clouds","icon":"04d"}]}' t = sjson.decode(forecast) for k,v in pairs(t) do print(k,v) end print(t.weather[1].main) print(t.weather[1].description) print(t.weather[1].icon) --------------------------------------- p = 222 d = "12.34" payload='{"result":[{"pres":'..(p)..',"temp":"'..(d)..'"}]}' print("\n"..payload) t = sjson.decode(payload) print(t.result[1].temp) print(t.result[1].pres.."\n") --------------------------------------- x = [[ Multiple lines of text can be enclosed in double square brackets.]] print(x) --------------------------------------- print("\n"..string.char(65)) print(65)