JSON is a popular format in which services exchange information. Functions allow parsing and modifying these payloads to integrate different services with each other.
To decode or encode JSON in a Lua function, import βjsonβ package:
-- import "json" package when working with JSONlocal json =require("json")-- example payload:-- {-- "user": "Peter",-- "age": 25,-- "city": "Edinburgh"-- }local request_payload, err = json.decode(r.RequestBody)if err thenerror(err) end-- now, request_payload is a normal JSON object and we-- can access individual valuesr:SetRequestBody(request_payload.user)-- request will now have a single value 'Peter' in the body
To encode a structure back into a JSON string:
-- import "json" package when working with JSONlocal json =require("json")-- constructing a new object that we will encode-- into a JSON stringlocal new_payload = { action="hello", message="world",}-- encodinglocal encoded_payload, err = json.encode(new_payload)if err thenerror(err) endr:SetRequestBody(encoded_payload)-- webhook request body is now changed to:-- {-- "action": "hello",-- "message: "world"-- }