Skip to main content

JSONTools

Struct JSONTools 

Source
pub struct JSONTools { /* private fields */ }
Expand description

Unified JSON Tools API with builder pattern for both flattening and unflattening operations

This is the unified interface for all JSON manipulation operations. It provides a single entry point for all JSON manipulation operations with a consistent builder pattern.

Implementations§

Source§

impl JSONTools

Source

pub fn new() -> Self

Create a new JSONTools instance with default settings

Source

pub fn flatten(self) -> Self

Set the operation mode to flatten

Source

pub fn unflatten(self) -> Self

Set the operation mode to unflatten

Source

pub fn normal(self) -> Self

Set the operation mode to normal (apply transformations without flatten/unflatten)

In normal mode, key/value replacements, filtering, and type conversion are applied recursively to the JSON structure without flattening or unflattening it.

§Example
use json_tools_rs::{JSONTools, JsonOutput};

let json = r#"{"Name": "John", "Age": "30", "Active": "true"}"#;
let result = JSONTools::new()
    .normal()
    .lowercase_keys(true)
    .auto_convert_types(true)
    .execute(json).unwrap();

match result {
    JsonOutput::Single(output) => {
        assert!(output.contains(r#""name""#));
        assert!(output.contains(r#":30"#) || output.contains(r#": 30"#));
    }
    _ => unreachable!(),
}
Source

pub fn separator(self, separator: impl Into<String>) -> Self

Set the separator used for nested keys (default: “.”)

Empty separators are rejected at execute() time with a descriptive error.

Source

pub fn lowercase_keys(self, value: bool) -> Self

Convert all keys to lowercase

Source

pub fn key_replacement( self, find: impl Into<String>, replace: impl Into<String>, ) -> Self

Add a key replacement pattern

Patterns are literal (exact substring match) by default. Wrap a pattern in r'...' (e.g. r'^admin_') to use standard Rust regex syntax instead. A malformed r'...' pattern is silently treated as “no match” rather than raising an error. Works for both flatten and unflatten operations.

§Examples
use json_tools_rs::{JSONTools, JsonOutput};

// Regex pattern, via the r'...' wrapper
let json = r#"{"user_name": "John", "admin_name": "Jane"}"#;
let result = JSONTools::new()
    .flatten()
    .key_replacement("r'(user|admin)_'", "person_")
    .execute(json).unwrap();

// Literal pattern (the default -- no r'...' wrapper)
let result2 = JSONTools::new()
    .flatten()
    .key_replacement("user_", "person_")
    .execute(json).unwrap();
Source

pub fn value_replacement( self, find: impl Into<String>, replace: impl Into<String>, ) -> Self

Add a value replacement pattern

Patterns are literal (exact substring match) by default. Wrap a pattern in r'...' (e.g. r'^admin_') to use standard Rust regex syntax instead. A malformed r'...' pattern is silently treated as “no match” rather than raising an error. Works for both flatten and unflatten operations.

§Examples
use json_tools_rs::{JSONTools, JsonOutput};

// Regex pattern, via the r'...' wrapper
let json = r#"{"role": "super", "level": "admin"}"#;
let result = JSONTools::new()
    .flatten()
    .value_replacement("r'^(super|admin)$'", "administrator")
    .execute(json).unwrap();

// Literal pattern (the default -- no r'...' wrapper)
let result2 = JSONTools::new()
    .flatten()
    .value_replacement("@example.com", "@company.org")
    .execute(json).unwrap();
Source

pub fn remove_empty_strings(self, value: bool) -> Self

Remove keys with empty string values

Works for both flatten and unflatten operations:

  • In flatten mode: removes flattened keys that have empty string values
  • In unflatten mode: removes keys from the unflattened JSON structure that have empty string values
Source

pub fn remove_nulls(self, value: bool) -> Self

Remove keys with null values

Works for both flatten and unflatten operations:

  • In flatten mode: removes flattened keys that have null values
  • In unflatten mode: removes keys from the unflattened JSON structure that have null values
Source

pub fn remove_empty_objects(self, value: bool) -> Self

Remove keys with empty object values

Works for both flatten and unflatten operations:

  • In flatten mode: removes flattened keys that have empty object values
  • In unflatten mode: removes keys from the unflattened JSON structure that have empty object values
Source

pub fn remove_empty_arrays(self, value: bool) -> Self

Remove keys with empty array values

Works for both flatten and unflatten operations:

  • In flatten mode: removes flattened keys that have empty array values
  • In unflatten mode: removes keys from the unflattened JSON structure that have empty array values
Source

pub fn handle_key_collision(self, value: bool) -> Self

Handle key collisions by collecting values into arrays

When enabled, collect all values that would have the same key into an array. Works for all operations (flatten, unflatten, normal).

Source

pub fn auto_convert_types(self, enable: bool) -> Self

Enable automatic type conversion from strings to numbers and booleans

When enabled, the library will attempt to convert string values to numbers or booleans:

  • Numbers: “123” -> 123, “1,234.56” -> 1234.56, “$99.99” -> 99.99, “1e5” -> 100000
  • Booleans: “true”/“TRUE”/“True” -> true, “false”/“FALSE”/“False” -> false

If conversion fails, the original string value is kept. No errors are thrown.

Works for all operations (flatten, unflatten, normal).

§Example
use json_tools_rs::{JSONTools, JsonOutput};

let json = r#"{"id": "123", "price": "1,234.56", "active": "true"}"#;
let result = JSONTools::new()
    .flatten()
    .auto_convert_types(true)
    .execute(json)
    .unwrap();

match result {
    JsonOutput::Single(output) => {
        // Result: {"id": 123, "price": 1234.56, "active": true}
        assert!(output.contains(r#""id":123"#));
        assert!(output.contains(r#""price":1234.56"#));
        assert!(output.contains(r#""active":true"#));
    }
    _ => unreachable!(),
}
Source

pub fn parallel_threshold(self, threshold: usize) -> Self

Set the minimum batch size for parallel processing (only available with ‘parallel’ feature)

When processing multiple JSON documents, this threshold determines when to use parallel processing. Batches smaller than this threshold will be processed sequentially to avoid the overhead of thread spawning.

Default: 100 items (can be overridden with JSON_TOOLS_PARALLEL_THRESHOLD environment variable)

§Arguments
  • threshold - Minimum number of items in a batch to trigger parallel processing
§Example
use json_tools_rs::JSONTools;

let tools = JSONTools::new()
    .flatten()
    .parallel_threshold(50); // Only use parallelism for batches of 50+ items
Source

pub fn num_threads(self, num_threads: Option<usize>) -> Self

Configure the number of threads for parallel processing

By default, the number of logical CPUs is used. This method allows you to override that behavior for specific workloads or resource constraints.

§Arguments
  • num_threads - Number of threads to use (None = use system default)
§Examples
use json_tools_rs::JSONTools;

let tools = JSONTools::new()
    .flatten()
    .num_threads(Some(4)); // Use exactly 4 threads
Source

pub fn nested_parallel_threshold(self, threshold: usize) -> Self

Configure the threshold for nested parallel processing within individual JSON documents

When flattening or unflattening a single large JSON document, this threshold determines when to parallelize the processing of objects and arrays. Only objects/arrays with more than this many keys/items will be processed in parallel.

Default: 100 (can be overridden with JSON_TOOLS_NESTED_PARALLEL_THRESHOLD environment variable)

§Arguments
  • threshold - Minimum number of keys/items to trigger nested parallelism
§Examples
use json_tools_rs::JSONTools;

let tools = JSONTools::new()
    .flatten()
    .nested_parallel_threshold(200); // Only parallelize objects/arrays with 200+ items
Source

pub fn max_array_index(self, max: usize) -> Self

Set the maximum array index allowed during unflattening

This prevents denial-of-service attacks where a malicious flattened key like "items.999999999" would cause allocation of a massive array. Keys with array indices exceeding this limit will produce an error during unflattening.

Default: 100,000 (can be overridden with JSON_TOOLS_MAX_ARRAY_INDEX environment variable)

Source

pub fn execute<'a, T>( &self, json_input: T, ) -> Result<JsonOutput, JsonToolsError>
where T: Into<JsonInput<'a>>,

Execute the configured operation on the provided JSON input

This method performs the selected operation based on the mode set by calling .flatten(), .unflatten(), or .normal(). If no mode was set, an error is returned.

§Arguments
  • json_input - JSON input that can be a single string, multiple strings, or other supported types
§Returns
  • Result<JsonOutput, Box<dyn Error>> - The processed JSON result or an error
§Errors
  • Returns an error if no operation mode has been set
  • Returns an error if the JSON input is invalid
  • Returns an error if processing fails for any other reason

Trait Implementations§

Source§

impl Clone for JSONTools

Source§

fn clone(&self) -> JSONTools

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 Debug for JSONTools

Source§

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

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

impl Default for JSONTools

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> 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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
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 = 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.