Webhook Relay
Search…
Working with JSON
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:
1
-- import "json" package when working with JSON
2
local json = require("json")
3
​
4
-- example payload:
5
-- {
6
-- "user": "Peter",
7
-- "age": 25,
8
-- "city": "Edinburgh"
9
-- }
10
​
11
local request_payload, err = json.decode(r.RequestBody)
12
if err then error(err) end
13
​
14
-- now, request_payload is a normal JSON object and we
15
-- can access individual values
16
​
17
r:SetRequestBody(request_payload.user)
18
-- request will now have a single value 'Peter' in the body
Copied!
To encode a structure back into a JSON string:
1
-- import "json" package when working with JSON
2
local json = require("json")
3
​
4
-- constructing a new object that we will encode
5
-- into a JSON string
6
local new_payload = {
7
action= "hello",
8
message= "world"}
9
​
10
-- encoding
11
local encoded_payload, err = json.encode(new_payload)
12
if err then error(err) end
13
​
14
r:SetRequestBody(encoded_payload)
15
-- webhook request body is now changed to:
16
-- {
17
-- "action": "hello",
18
-- "message: "world"
19
-- }
Copied!
Last modified 7mo ago
Copy link