Lua and JSON
I've been working on a Lightroom plugin for a project of mine, and I need to integrate it with my JSON-based web-service. I haven't found a single tool to make the process easy - I've had to use two tools, JSON4LUA and a JSON library from Jeffrey Friedl. What follows is the code I've written using the two.
local http = require("socket.http")
local ltn12 = require("ltn12")
local mime = require("mime")
baseUrl = "http://localhost:8888/webservice/accounts/ckaminski"
local t1 = { }
r, c, t = http.request {
url = baseUrl,
headers = { ["Authorization"] = "Basic " .. (mime.b64("ckaminski:fizzbuzz")) },
sink = ltn12.sink.table(t1)
}
local jsonstr = DataDumper(t1)
-- strip some wrapper text.
jsonstr = string.gsub(jsonstr, "return {", "")
jsonstr = string.gsub(jsonstr, "}$", "")
local JSON = require("JSON")
require("json4lua")
local jsontxt = JSON:decode(jsonstr)
print("JSON decoded: " .. jsontxt)
local objects = json.decode(jsontxt)
local quota = objects["account"]["UserQuota"]
table.foreach(objects["account"], print)
table.foreach(quota, print)
The JSON string returned to the Lua client from the webserver looks like this in Lua:
"{\"account\":{\"Username\":\"ckaminski\",\"EmailAddress\":\"ckaminski@example.com\",\"UserQuota\":{\"QuotaLeftMB\":10000,\"QuotaMaxMB\":10000,\"QuotaUsedMB\":0},\"EncryptedPassword\":\"fizzbuzz\",\"DisplayName\":\"Chris Kaminski\"}}"
The actual JSON string returned is:
{"account":{"Username":"ckaminski","EmailAddress":"ckaminski@example.com","UserQuota":{"QuotaLeftMB":10000,"QuotaMaxMB":10000,"QuotaUsedMB":0},"EncryptedPassword":"fizzbuzz","DisplayName":"Chris Kaminski"}}