json.escape
Available inall subroutines.
Escapes characters of a UTF-8 encoded Unicode string using JSON-style escape sequences.
The escaping rules are as follows, in priority order:
- If the code point is the double quote (0x22), it is escaped as
\"
(backslash double quote). - If the code point is the backslash (0x5C), it is escaped as
\\
(double backslash). - 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)
- 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 theH`HHH
is the hexadecimal value of the code point. This is similar to the Unicode notationU+HHHHH
, though note the difference between lowercaseu
and uppercaseU
. - 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
. - 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). - The above rules together mean that no code points above 0x7F and less than
0x10000 are converted to
\\uHHHH
except theU+2028
andU+2029
. - 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
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 code examples. Examples apply VCL to real-world use cases and can be deployed as they are, or adapted for your own service. See the full list of code examples for more inspiration.
Click RUN on a sample below 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 geolocation 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.