JSON Template in Lua

406 Views Asked by At

I have a JSON object which I would like to templatize in lua. For example:

{
  "type":"email",
  "version":"1.0",
  "account":"%emailId%"
}

I would like to substitute the %emailId% with a list of e-mail ids. Is there a templatization support for JSON in lua?

2

There are 2 best solutions below

0
Jack Taylor On BEST ANSWER

No, there is no built-in support for either JSON or templating in the core Lua language or libraries. There are a number of JSON modules available, but I'm not sure whether any of them have template support. You might have to write a templating function yourself, but it probably won't be too hard - it's just a matter of iterating over all the string values with the JSON module and using string.gsub on them.

0
kallaballa On

Though it isn't intended for JSON you can use lua-resty-template.

user.json:

{ "user": "{{username}}" }

lua-code:

local template = require "resty.template"
local result = template.compile("user.json")({ username = "someone" })
print(result);

result:

{ "user": "someone" }