JSON Encoding
How to encode and decode JSON in Huk Relay Functions
JSON is a popular format in which services exchange information. Functions allow parsing and modifying these payloads to integrate different services with each other.
Some of the examples that you can do:
- Decode Stripe webhook and encode it into a Slack or Discord notification.
- Change Mailgun delivery notification into a Discord message.
- Send an email when a change is pushed to a specific Bitbucket branch.
Decode JSON
To decode or encode JSON in a JavaScript function, use the global JSON object:
// example payload:
// {
// "user": "Peter",
// "age": 25,
// "city": "Edinburgh"
// }
var payload = JSON.parse(request.body);
// now, payload is a normal JavaScript object and we
// can access individual values
request.body = payload.user;
// request will now have a single value 'Peter' in the bodyEncode to JSON
To encode a structure back into a JSON string:
// constructing a new object that we will encode
// into a JSON string
var newPayload = {
action: "hello",
message: "world"
};
// encoding
request.body = JSON.stringify(newPayload);
// webhook request body is now changed to:
// {
// "action": "hello",
// "message: "world"
// }
Huk Relay Docs