---
title: json.escape
summary: null
url: >-
  https://www.fastly.com/documentation/reference/vcl/functions/strings/json-escape
---

```
STRING json.escape(STRING string)
```

**Available in:** all subroutines

Escapes characters of a UTF-8 encoded Unicode string using JSON-style
escape sequences.

The escaping rules are as follows, in priority order:

1. If the code point is the double quote (0x22), it is escaped as `\"`
   (backslash double quote).
2. If the code point is the backslash (0x5C), it is escaped as `\\` (double
   backslash).
3. If the code point is one of the following control characters, it is escaped
   as described:
   ```
   - ``\b`` (0x08, backspace)
   - ``\t`` (0x09, horizontal tab)
   - ``\n`` (0x0A, newline)
   - ``\f`` (0x0C, form feed)
   - ``\r`` (0x0D, carriage return)
   ```
4. If the code point is less than or equal to 0x1F, or equal to 0x7F,
   0x2028, or 0x2029 (in other words, a control character not explicitly listed
   above), it is escaped as `\uHHHH` where the `HHHH` is the hexadecimal
   value of the code point. This is similar to the Unicode notation `U+HHHHH`,
   though note the difference between lowercase `u` and uppercase `U`.
5. If none of the above rules match and there is a sequence of valid UTF-8 bytes,
   the bytes are passed through as-is, regardless of whether the code point is
   inside or beyond the Basic Multilingual Plane (U+0000-U+FFFF). For example,
   `a` would be passed through for U+0061, `✨` would be passed through for
   U+2728 (UTF-8 bytes: 0xE2 0x9C 0xA8), and `😂` would be passed through for
   U+1F602 (UTF-8 bytes: 0xF0 0x9F 0x98 0x82). Note that this function never
   produces UTF-16 surrogate pairs; every valid code point, including those
   beyond U+FFFF, is passed through as UTF-8 rather than encoded as a pair of
   `\uHHHH` escapes.
6. The above rules together mean that no code point above 0x7F is converted
   to `\uHHHH` except `U+2028` and `U+2029`.
7. Finally, if there is a byte sequence of invalid UTF-8, the conversion fails
   and the string value is _not set_.

Some examples:

| Input             | json.escape()                     |
| :---------------- | :-------------------------------- |
| `abc123`          | `abc123`                          |
| `/foo/bar`        | `/foo/bar`                        |
| `?p=q&x=y`        | `?p=q&x=y`                        |
| `"`               | `\"`                              |
| `\`               | `\\`                              |
| (newline)         | `\n`                              |
| (tab)             | `\t`                              |
| `αβγ`             | `αβγ` (alpha beta gamma in UTF-8) |
| (byte 0xff)       | conversion error, _not set_       |
| `a` + (byte 0xcc) | conversion error, _not set_       |

## Example

```vcl
declare local var.json STRING;
set var.json = "{ %22city%22: %22" + json.escape(client.geo.city.utf8) + "%22 }";
# var.json is now e.g. { "city": "london" }
```
