JsonFormatter

Struct JsonFormatter 

Source
pub struct JsonFormatter<'a, 'b> { /* private fields */ }
Expand description

A formatter for JSON values that controls the layout and formatting of the output.

JsonFormatter wraps the std::fmt::Formatter and provides methods specifically designed for generating well-formed JSON with customizable formatting options like indentation and spacing.

This formatter is primarily used when implementing the DisplayJson trait or when using the json() function for in-place JSON generation.

§Examples

Basic usage with the json() function:

use nojson::json;

// Generate compact JSON
let compact = json(|f| f.value([1, 2, 3]));
assert_eq!(compact.to_string(), "[1,2,3]");

// Generate pretty-printed JSON
let pretty = json(|f| {
    f.set_indent_size(2);
    f.set_spacing(true);
    f.value([1, 2, 3])
});

assert_eq!(
    format!("\n{}", pretty),
    r#"
[
  1,
  2,
  3
]"#
);

Implementations§

Source§

impl<'a, 'b> JsonFormatter<'a, 'b>

Source

pub fn value<T: DisplayJson>(&mut self, value: T) -> Result

Formats a value that implements the DisplayJson trait.

This is the primary method for writing a value to the JSON output.

§Examples
use nojson::json;

let output = json(|f| f.value([1, 2, 3]));
assert_eq!(output.to_string(), "[1,2,3]");
Source

pub fn string<T: Display>(&mut self, content: T) -> Result

Formats a value as a JSON string with proper escaping.

This method handles the necessary escaping of special characters in JSON strings, including quotes, backslashes, control characters, etc.

§Examples
use nojson::json;

let output = json(|f| f.string("Hello\nWorld"));
assert_eq!(output.to_string(), r#""Hello\nWorld""#);
Source

pub fn array<F>(&mut self, f: F) -> Result
where F: FnOnce(&mut JsonArrayFormatter<'a, 'b, '_>) -> Result,

Creates a JSON array with the provided formatting function.

This method starts a new JSON array and provides a JsonArrayFormatter to the callback function for adding elements to the array. It handles proper indentation, spacing, and brackets placement.

§Examples
use nojson::json;

let output = json(|f| {
    f.array(|f| {
        f.element(1)?;
        f.element(2)?;
        f.element(3)
    })
});
assert_eq!(output.to_string(), "[1,2,3]");

// With pretty-printing
let pretty = json(|f| {
    f.set_indent_size(2);
    f.set_spacing(true);
    f.array(|f| {
        f.element(1)?;
        f.element(2)?;
        f.element(3)
    })
});
Source

pub fn object<F>(&mut self, f: F) -> Result
where F: FnOnce(&mut JsonObjectFormatter<'a, 'b, '_>) -> Result,

Creates a JSON object with the provided formatting function.

This method starts a new JSON object and provides a JsonObjectFormatter to the callback function for adding members to the object. It handles proper indentation, spacing, and braces placement.

§Examples
use nojson::json;
use std::collections::HashMap;

let output = json(|f| {
    f.object(|f| {
        f.member("name", "Alice")?;
        f.member("age", 30)
    })
});
assert_eq!(output.to_string(), r#"{"name":"Alice","age":30}"#);

// With pretty-printing
let pretty = json(|f| {
    f.set_indent_size(2);
    f.set_spacing(true);
    f.object(|f| {
        f.member("name", "Alice")?;
        f.member("age", 30)
    })
});
Source

pub fn inner_mut(&mut self) -> &mut Formatter<'b>

Returns a mutable reference to the inner std::fmt::Formatter.

This method provides direct access to the wrapped formatter, which can be useful for implementing custom formatting logic for primitive types.

§Note

It is the responsibility of the user to ensure that the content written to the inner formatter is valid JSON.

Source

pub fn get_level(&self) -> usize

Returns the current indentation level.

The indentation level increases when entering arrays and objects, and decreases when exiting them.

Source

pub fn get_indent_size(&self) -> usize

Returns the number of spaces used for each indentation level.

Source

pub fn set_indent_size(&mut self, size: usize)

Sets the number of spaces used for each indentation level.

Note that this setting only affects the current and higher indentation levels.

Source

pub fn get_spacing(&self) -> bool

Returnes whether inserting a space after ‘:’, ‘,’, and ‘{’.

Source

pub fn set_spacing(&mut self, enable: bool)

Sets whether inserting a space after ‘:’, ‘,’, and ‘{’.

Note that this setting only affects the current and higher indentation levels.

Trait Implementations§

Source§

impl Debug for JsonFormatter<'_, '_>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'a, 'b> Freeze for JsonFormatter<'a, 'b>

§

impl<'a, 'b> !RefUnwindSafe for JsonFormatter<'a, 'b>

§

impl<'a, 'b> !Send for JsonFormatter<'a, 'b>

§

impl<'a, 'b> !Sync for JsonFormatter<'a, 'b>

§

impl<'a, 'b> Unpin for JsonFormatter<'a, 'b>

§

impl<'a, 'b> !UnwindSafe for JsonFormatter<'a, 'b>

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> 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, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.