Skip to main content

Format

Struct Format 

Source
#[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_safe also escapes <, >, and &, so the output can sit inside an HTML <script> element or attribute without ending it (</script> cannot appear in it);
  • ascii escapes 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). The plain formats copy a RawValue’s text as it is, so U+2028 and U+2029 inside its strings are written raw there (valid JSON, but not JavaScript source before ES2019); every string the writers make has them escaped. For output pasted into JavaScript, use html_safe, which escapes them in raw text too.

Two options change the text of floats written from Rust values (ValueWriter::f64 and f32), for output that must match another writer’s byte for byte: exponent_plus writes 1e+16 for 1e16, and even_ties changes which of two equally close shortest texts is written. A Number keeps its own text in every format. 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

Source

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]}"#);
Source

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]");
Source

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}");
Source

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\"");
Source

pub const fn ascii(self, on: bool) -> Self

Whether to escape every non-ASCII character, so the output is pure ASCII.

§Examples
use jsonx_lib::{to_string_with, Format};

assert_eq!(to_string_with("\u{e9}\u{1f600}", Format::compact().ascii(true)), "\"\\u00e9\\ud83d\\ude00\"");
Source

pub const fn exponent_plus(self, on: bool) -> Self

Whether to write the + of a positive exponent in float text: 1e+16 rather than 1e16, as serde_json (1.0.147 and later), JavaScript and Python write it. Negative exponents always have their -; floats from 1e-5 up to below 1e16 are written as decimals and have no exponent.

§Examples
use jsonx_lib::{to_string_with, Format};

let plus = Format::compact().exponent_plus(true);
assert_eq!(to_string_with(&[1e16, 2.5e-7, 0.5], plus), "[1e+16,2.5e-7,0.5]");
assert_eq!(to_string_with(&1e16, Format::compact()), "1e16");
Source

pub const fn even_ties(self, on: bool) -> Self

Whether an exact tie in float text goes to the even digit.

A float is written as the shortest decimal that reads back as it, and of those the closest. Rarely two are equally close (the float lies exactly halfway between them; it takes 16 or 17 significant digits for an f64). Both read back as the same float. By default the higher one is written, as Rust’s own formatting ({}, {:e}) picks it; with this option, the one whose last digit is even, as serde_json, Java, JavaScript and Python pick it.

§Examples
use jsonx_lib::{to_string_with, Format};

// 164696460098373.625 lies exactly between ...373.62 and ...373.63.
let x = 164_696_460_098_373.625_f64;
assert_eq!(to_string_with(&x, Format::compact()), "164696460098373.63");
assert_eq!(to_string_with(&x, Format::compact().even_ties(true)), "164696460098373.62");
assert_eq!(format!("{x}"), "164696460098373.63");
Source

pub const fn is_pretty(&self) -> bool

Whether this is an indented layout.

§Examples
assert!(jsonx_lib::Format::pretty().is_pretty());
assert!(!jsonx_lib::Format::default().is_pretty());

Trait Implementations§

Source§

impl Clone for Format

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for Format

Source§

impl Debug for Format

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Format

Source§

impl Eq for Format

Source§

impl Hash for Format

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Format

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Format

Auto Trait Implementations§

§

impl Forget for Format

§

impl Freeze for Format

§

impl Move for Format

§

impl RefUnwindSafe for Format

§

impl Send for Format

§

impl Sync for Format

§

impl Unpin for Format

§

impl UnsafeUnpin for Format

§

impl UnwindSafe for Format

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.