---
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 ``H`HHH`` 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 the code point is beyond 0xFFFF (that is, beyond the Basic Multilingual
   Plane of Unicode), the code point is converted to _UTF-16 surrogate pair_
   with the `\\u` notation: for example, the U+1F601 or `😁` (UTF-8 bytes:
   0xF0 0x9F 0x98 0x81) is escaped as `\uD83D\uDE00`.
6. If none of the above rules match and there is a sequence of valid UTF-8 bytes,
   the bytes are passed through as-is. For example, `a` would be passed through
   for U+0061 or `😂` would be passed through for U+1F602
   (UTF-8 bytes: 0xF0 0x9F 0x98 0x82).
7. The above rules together mean that no code points above 0x7F and less than
   0x10000 are converted to `\\uHHHH` except the `U+2028` and `U+2029`.
8. 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" }
```
