#[non_exhaustive]pub struct Format { /* private fields */ }Expand description
How the writers lay out and escape their output.
The default is compact JSON (no whitespace) with the escaping described
on write_string: quotes, backslashes, control
characters, and U+2028/U+2029, and nothing else. pretty
is the to_string_pretty layout. Two stricter
escapings are available for output that is embedded somewhere JSON’s own
rules are not enough:
html_safealso escapes<,>, and&, so the output can sit inside an HTML<script>element or attribute without ending it (</script>cannot appear in it);asciiescapes every non-ASCII character as\uXXXX(a surrogate pair above U+FFFF), for channels that are not 8-bit clean.
Both apply to everything written, RawValue text
included (its strings are escaped the same way). Every format writes
valid JSON that reads back as the same value (for objects without
repeated keys: the writers do not check for them; see
ObjectWriter); the formats differ only in
bytes.
The struct is #[non_exhaustive]: build it from Format::compact or
Format::pretty and the with_* methods.
§Examples
use jsonx_lib::{json, to_string_with, Format};
let v = json!({ "html": "</script>", "word": "caf\u{e9}" });
let safe = to_string_with(&v, Format::compact().html_safe(true).ascii(true));
assert!(!safe.contains('<') && safe.is_ascii());
assert_eq!(jsonx_lib::parse(&safe)?, v);
let wide = to_string_with(&json!([1]), Format::pretty().with_indent(4));
assert_eq!(wide, "[\n 1\n]");Implementations§
Source§impl Format
impl Format
Sourcepub const fn compact() -> Self
pub const fn compact() -> Self
Compact JSON: no whitespace at all. The default.
§Examples
use jsonx_lib::{json, to_string_with, Format};
assert_eq!(to_string_with(&json!({ "a": [1, 2] }), Format::compact()), r#"{"a":[1,2]}"#);Sourcepub const fn pretty() -> Self
pub const fn pretty() -> Self
The indented layout of to_string_pretty:
one member or item per line, two spaces per level, ": " after keys,
empty containers as [] and {}, no trailing newline.
§Examples
use jsonx_lib::{json, to_string_with, Format};
assert_eq!(to_string_with(&json!([1]), Format::pretty()), "[\n 1\n]");Sourcepub const fn with_indent(self, spaces: u8) -> Self
pub const fn with_indent(self, spaces: u8) -> Self
The indented layout with spaces spaces per level (0 puts each
member on its own line without indenting it).
§Examples
use jsonx_lib::{json, to_string_with, Format};
assert_eq!(to_string_with(&json!({ "a": 1 }), Format::compact().with_indent(1)), "{\n \"a\": 1\n}");Sourcepub const fn html_safe(self, on: bool) -> Self
pub const fn html_safe(self, on: bool) -> Self
Whether to also escape <, >, and & (as \u003c, \u003e,
\u0026), so the output is safe inside HTML.
§Examples
use jsonx_lib::{to_string_with, Format};
let text = to_string_with("</script>", Format::compact().html_safe(true));
assert_eq!(text, "\"\\u003c/script\\u003e\"");