json.escape

STRINGjson.escapeSTRINGstring

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)
  1. 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.
  2. 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.
  3. 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).
  4. 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.
  5. Finally, if there is a byte sequence of invalid UTF-8, the conversion fails and the string value is not set.

Some examples:

Inputjson.escape()
abc123abc123
/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

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"}

Try it out

json.escape is used in the following solution recipes, which show real world use cases. Click RUN to provision a Fastly service, execute the code on Fastly, and see how the function behaves.

Geo-IP API at the edge

Create an API endpoint for fetching GeoIP data for the requesting browser, implemented 100% at the edge. The response should show your current approximate location, but no requests to any origin servers.

Comprehensive logging

Fastly offers a myriad of different variables that you can log. See and test a large collection here.

User contributed notes

We welcome comments that add use cases, ideas, tips, and caveats. All comments will be moderated before publication. To post support questions, visit our support center and we'll find you the help you need.