Hi all,
This is likely trivial but it took me as a noob several hours to do.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | http = require("socket.http") crypto = require("crypto") ltn12 = require("ltn12") url = require("socket.url") require("Json") local commands_json = { { ["command"] = "search" } } local json = {} json.api_key = "6_192116334" json.ver = 1 json.commands_json = Json.Encode(commands_json) json.commands_hash = crypto.digest(crypto.md5, json.commands_json .. 'hkjhkjhkjh') local post = "api=" .. url.escape(Json.Encode(json)) local response = {} local r, c, h = http.request { url = "http://127.0.0.1/?page=api", method = "POST", headers = { ["content-length"] = #post, ["Content-Type"] = "application/x-www-form-urlencoded" }, source = ltn12.source.string(post), sink = ltn12.sink.table(response) } local path = system.pathForFile("r.txt", system.DocumentsDirectory) local file = io.open (path, "w") file:write (Json.Encode(json) .. "\n") file:write (post .. "\n") file:write (response[1] .. "\n") io.close (file) json = Json.Decode(table.concat(response,'')) native.showAlert("hey", json.commands[1].tot_nbr_rows) |
Just fyi, the response looks like
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | { "e":false, "commands":[ { "tot_nbr_rows":2, "nbr_footage":2, "nbr_music":0, "nbr_sfx":0, "icon_base":"http:\/\/127.0.0.1\/pretendcdn\/", "flv_base":"http:\/\/d36cfktcezzxd.cloudfront.net\/", "items":[ { "id":125, "vs":2, "ox":1440, "oy":1080, "ar":2 }, { "id":127, "vs":7, "ox":720, "oy":1280, "ar":4 } ] } ] } |
Best regards,
Marcus
Hi Tom,
It's the Json lib that was recommended in another thread "Json lib that works":
http://www.chipmunkav.com/downloads/Json.lua
The only possible gotyas would be that the response should be treated as an array (which the type of sink gives away) and that Json decoded arrays needs to honor the Lua array 1.. index thing. Me as a programmer of other languages finds that to be wtf.
Marcus
JSON is now integrated into Corona, so no need to include an external module. Here's a tutorial on how to use it, just posted:
http://blog.anscamobile.com/2011/08/tutorial-exploring-json-usage-in-corona/
Hi Marcus,
Thanks for sharing your code. Sample code is always nice to have. Where did you find the JSON Lua Library?
Tom