pub fn escape(str: &str, mode: EscapeMode) -> String
Expand description
Escape a string according to JSONPath rules in a given quotation context.
§Quotes
Processing quotes, '
and "
, depends on the mode
:
- in
EscapeMode::SingleQuoted
, the string is escaped as if written in a single-quoted name selector['<str>']
; single quotes are escaped as\'
, double-quotes are copied as-is. - in
EscapeMode::DoubleQuoted
, the string is escaped as if written in double-quotes, which is the same as a member name in a JSON document or a double-quoted name selector["<str>"]
; double quotes are escaped as\"
, single quotes are copied as-is.
§Examples
let result_single = str::escape(r#"'rust' or "rust"\n"#, EscapeMode::SingleQuoted);
let result_double = str::escape(r#"'rust' or "rust"\n"#, EscapeMode::DoubleQuoted);
assert_eq!(result_single, r#"\'rust\' or "rust"\\n"#);
assert_eq!(result_double, r#"'rust' or \"rust\"\\n"#);
§Control characters
Control characters (U+0000 to U+001F) are escaped as special sequences
where possible, e.g. Form Feed U+000C is escaped as \f
.
Other control sequences are escaped as a Unicode sequence, e.g.
a null byte is escaped as \u0000
.
§Examples
let result = str::escape("\u{08}\u{09}\u{0A}\u{0B}\u{0C}\u{0D}", EscapeMode::DoubleQuoted);
assert_eq!(result, r"\b\t\n\u000b\f\r");
§Other
Characters that don’t have to be escaped are not.
§Examples
let result = str::escape("🦀", EscapeMode::DoubleQuoted);
assert_eq!(result, "🦀");
Among other things, this means Unicode escapes are only produced for control characters.