Formatter

Struct Formatter 

Source
pub struct Formatter {
    pub options: FracturedJsonOptions,
    pub string_length_func: Arc<dyn Fn(&str) -> usize + Send + Sync>,
    /* private fields */
}
Expand description

The main JSON formatter.

Formatter takes JSON input (either as text or Rust values) and produces human-readable, well-formatted output according to the configured options.

§Example

use fracturedjson::Formatter;

let mut formatter = Formatter::new();

// Format JSON text
let output = formatter.reformat(r#"{"a":1,"b":2}"#, 0).unwrap();
assert!(output.contains("\"a\": 1"));

// Minify JSON
let compact = formatter.minify(r#"{ "a": 1, "b": 2 }"#).unwrap();
assert_eq!(compact, r#"{"a":1,"b":2}"#);

§Reusing the Formatter

A single Formatter instance can be reused for multiple formatting operations. The configuration in options persists across calls, but internal buffers are reset for each operation.

Fields§

§options: FracturedJsonOptions

Configuration options that control formatting behavior. Modify these before calling formatting methods.

§string_length_func: Arc<dyn Fn(&str) -> usize + Send + Sync>

Function used to calculate string display width.

By default, this counts Unicode characters. For accurate alignment with East Asian wide characters, you can provide a custom function that accounts for character display widths (e.g., using the unicode-width crate).

§Example

use fracturedjson::Formatter;
use std::sync::Arc;

let mut formatter = Formatter::new();

// Use a custom width function (example with simple char count)
formatter.string_length_func = Arc::new(|s: &str| s.chars().count());

Implementations§

Source§

impl Formatter

Source

pub fn new() -> Self

Creates a new Formatter with default options.

§Example
use fracturedjson::Formatter;

let formatter = Formatter::new();
Source

pub fn string_length_by_char_count(value: &str) -> usize

Default string length function that counts Unicode characters.

This is the default implementation used for calculating display widths. For most Western text, this produces correct alignment. For text containing East Asian wide characters, consider using a width-aware function.

Source

pub fn reformat( &mut self, json_text: &str, starting_depth: usize, ) -> Result<String, FracturedJsonError>

Reformats JSON text according to the current options.

Parses the input JSON and produces formatted output with proper indentation, line breaks, and alignment based on the configured options.

§Arguments
  • json_text - The JSON string to format
  • starting_depth - Initial indentation depth (usually 0)
§Returns

The formatted JSON string, or an error if parsing fails.

§Example
use fracturedjson::Formatter;

let mut formatter = Formatter::new();
let output = formatter.reformat(r#"{"name":"Alice","age":30}"#, 0).unwrap();

// Output will be nicely formatted with proper spacing
assert!(output.contains("\"name\": \"Alice\""));
Source

pub fn minify(&mut self, json_text: &str) -> Result<String, FracturedJsonError>

Minifies JSON text by removing all unnecessary whitespace.

Produces the most compact valid JSON representation of the input. Comments are handled according to options.comment_policy.

§Arguments
  • json_text - The JSON string to minify
§Returns

The minified JSON string, or an error if parsing fails.

§Example
use fracturedjson::Formatter;

let mut formatter = Formatter::new();
let input = r#"{
    "name": "Alice",
    "age": 30
}"#;

let output = formatter.minify(input).unwrap();
assert_eq!(output, r#"{"name":"Alice","age":30}"#);
Source

pub fn serialize_value( &mut self, value: &Value, starting_depth: usize, recursion_limit: usize, ) -> Result<String, FracturedJsonError>

Formats a serde_json::Value according to the current options.

This is useful when you already have parsed JSON data and want to format it without going through text parsing again.

§Arguments
  • value - The JSON value to format
  • starting_depth - Initial indentation depth (usually 0)
  • recursion_limit - Maximum nesting depth to prevent stack overflow
§Returns

The formatted JSON string, or an error if the recursion limit is exceeded.

§Example
use fracturedjson::Formatter;
use serde_json::json;

let mut formatter = Formatter::new();
let value = json!({"name": "Alice", "scores": [95, 87, 92]});

let output = formatter.serialize_value(&value, 0, 100).unwrap();
Source

pub fn serialize<T: Serialize>( &mut self, value: &T, starting_depth: usize, recursion_limit: usize, ) -> Result<String, FracturedJsonError>

Serializes any serde::Serialize type to formatted JSON.

This is the most convenient method for formatting Rust data structures. The value is first converted to a serde_json::Value, then formatted.

§Arguments
  • value - Any value implementing Serialize
  • starting_depth - Initial indentation depth (usually 0)
  • recursion_limit - Maximum nesting depth to prevent stack overflow
§Returns

The formatted JSON string, or an error if serialization fails.

§Example
use fracturedjson::Formatter;
use serde::Serialize;

#[derive(Serialize)]
struct Person {
    name: String,
    age: u32,
}

let person = Person {
    name: "Alice".into(),
    age: 30,
};

let mut formatter = Formatter::new();
let output = formatter.serialize(&person, 0, 100).unwrap();

assert!(output.contains("\"name\": \"Alice\""));

Trait Implementations§

Source§

impl Default for Formatter

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

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.