2808 explained code solutions for 75 technologies


nginx-luaHow to send JSON response


init_by_lua_block  {
  cjson = require("cjson")
}

server {
  location / {
    content_by_lua_block {
      local data = {name='Donald'}
      local output = cjson.encode(data)
      ngx.header["Content-type"] = 'application/json'
      ngx.say(output)
    }
  }
}ctrl + c
init_by_lua_block

nginx-lua module directive to run specified Lua code on server startup

require("cjson")

load module to manipulate JSON

content_by_lua_block

nginx-lua module directive to specify block of Lua code

{name='Donald'}

sample table to convert to JSON string

cjson.encode

encodes given Lua table to JSON string

ngx.header

allows to set response headers

application/json

set content type to application/json

ngx.say

output given text to client