SJSON decode
Posted:
Sun Dec 03, 2017 5:00 am
by Elektryczny22
Hello, could anyone explain to me how the sjon functions work? I try check value status. When i print result I give only table: 3fff0748 How to get the status value from this table?
CODE
http.get("http://xxx.xxx.xxx.xxx/Notification?recipient=2",nil, function(code, data)
local result = sjson.decode(data)
print("JSON .. ")
json_string = sjson.encode(result)
print(json_string)
--OUTPUT
JSON ..
{"notifications":[{"recipient":2,"sender":1,"id":2,"date":"2017-11-27 22:43:21","status":"new"}]}
Re: SJSON decode
Posted:
Thu Dec 07, 2017 9:07 am
by bondrogeen
data = '{"notifications":[{"recipient":2,"sender":1,"id":2,"date":"2017-11-27 22:43:21","status":"new"}]}'
ok, tablet_json = pcall(sjson.decode, data) -- that is more correct
if ok then
--[[
tablet_json = {table [array {table}]}
array starting point from 1
]]--
print(tablet_json.notifications[1].recipient) -- get value recipient = 2
--or
print(tablet_json['notifications'][1]['recipient'])
print(tablet_json.notifications[1].date) -- get value date = 2017-11-27 22:43:21
for key,value in pairs(tablet_json.notifications[1]) do -- get all tablet key and value
print(key,value)
end
else
print("failed to encode!")
end
tablet_json.notifications[1].recipient = 2017
json_string = sjson.encode(tablet_json)
print(json_string) --{"notifications":[{"recipient":2017,"sender":1,"id":2,"date":"2017-11-27 22:43:21","status":"new"}]}
Re: SJSON decode
Posted:
Tue Dec 12, 2017 4:00 am
by edtamarin
produces a Lua table with JSON property names as keys and property values as values. The structure and hierarchy is preserved. In your case, to get the
status field, you would have to do this:
Code: Select alllocal status = result.notifications[1].status
Note that in Lua, arrays start at 1, and so calling
result.notification[0] will produce an error.\
For further information on how the SJSON library works, I suggest you
read the docs.