---
title: "JSON encoding | WebhookRelay"
meta:
  "og:description": "How to encode and decode JSON in Webhook Relay Functions"
  "og:title": "JSON encoding"
  description: "How to encode and decode JSON in Webhook Relay Functions"
---

![Stripes](https://webhookrelay.com/docs/webhooks/functions/manipulating-json/images/stripes.svg)

Documentation

**Fundamentals**

# **JSON encoding**

How to encode and decode JSON in Webhook 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](#decode-json)

To decode JSON in a function:

```
// example payload:
// {
//   "user": "Peter",
//   "age": 25,
//   "city": "Edinburgh"
// }

const requestPayload = JSON.parse(r.body)

// now, requestPayload is a normal JSON object and we
// can access individual values

r.setBody(requestPayload.user)
// request will now have a single value 'Peter' in the body
```

```
-- import "json" package when working with JSON
local json = require("json")

-- example payload:
-- {
--   "user": "Peter",
--   "age": 25,
--   "city": "Edinburgh"
-- }

local request_payload, err = json.decode(r.RequestBody)
if err then error(err) end

-- now, request_payload is a normal JSON object and we
-- can access individual values

r:SetRequestBody(request_payload.user)
-- request will now have a single value 'Peter' in the body
```

## [Encode to JSON](#encode-to-json)

To encode a structure into a JSON string:

```
// constructing a new object that we will encode
// into a JSON string
const newPayload = {
    action: "hello",
    message: "world"
}

// encoding
const encodedPayload = JSON.stringify(newPayload)

r.setBody(encodedPayload)
// webhook request body is now changed to:
// {
//   "action": "hello",
//   "message": "world"
// }
```

```
-- import "json" package when working with JSON
local json = require("json")

-- constructing a new object that we will encode
-- into a JSON string
local new_payload = {
    action= "hello",
    message= "world"}

-- encoding
local encoded_payload, err = json.encode(new_payload)
if err then error(err) end

r:SetRequestBody(encoded_payload)
-- webhook request body is now changed to:
-- {
--   "action": "hello",
--   "message: "world"
-- }
```

Did this page help you?