jsonkit 0.2.2

A high-performance, lightweight Rust utility library engineered for robust JSON data processing.
Documentation
# 🚀 JSON KiT

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Rust](https://img.shields.io/badge/rust-1.70%2B-orange.svg)](https://www.rust-lang.org)
[![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://gitlab.com/lazylib/rs/jsonkit)

**JSON KiT** is a high-performance, lightweight Rust utility library engineered for robust JSON data processing.

Its primary mission is to bridge the gap between "JSON with Comments" (JSONC) and standard JSON parsers by efficiently sanitizing input strings, as well as providing tools for formatting JSON data.

---

## 📑 Table of Contents

- [Features]#-features
- [Installation]#-installation
- [Usage]#-usage
  - [Strip Comments]#strip-comments
  - [Minify JSON]#minify-json
  - [Format JSON]#format-json
  - [Validate JSON]#validate-json
- [API Reference]#-api-reference
- [Development]#%EF%B8%8F-development
- [License]#-license

---

## ✨ Features

- **🛡️ Comment Stripping**: Seamlessly removes standard C-style comments.
  - **Single-line**: `// comment`
  - **Multi-line**: `/* comment */`
- **📦 JSON Minification**: Efficiently removes whitespace to reduce payload size.
- **✅ JSON Validation**: Validates JSON strings to ensure they are well-formed.
- **🎨 JSON Formatting**: Prettify minified JSON with customizable indentation (spaces or tabs).
- **🧠 Context-Aware Parsing**: Intelligently distinguishes between actual comments and comment-like patterns within string literals.
- **⚡ High Performance**: Built on top of the `regex` crate with `OnceLock` for thread-safe, lazy initialization.

## 📦 Installation

Integrate `jsonkit` into your project by adding it to your `Cargo.toml`:

```toml
[dependencies]
jsonkit = { git = "https://gitlab.com/lazylib/rs/jsonkit" }
```

> **Note**: As this crate is hosted in a private/custom repository, please ensure your git configuration allows access if necessary.

## 🚀 Usage

### Strip Comments

Sanitizing JSON content is straightforward.

```rust
use jsonkit::strip_comments;

fn main() {
    // Input: JSON with comments (JSONC)
    let json_with_comments = r#"
    {
        // User profile configuration
        "name": "Alice",
        "age": 30, /* Age verified */
        "website": "http://example.com" // URL preserved
    }
    "#;

    // Process: Strip comments
    let clean_json = strip_comments(json_with_comments);

    // Output: Standard JSON
    println!("{}", clean_json);
}
```

### Minify JSON

Reduce the size of your JSON by removing unnecessary whitespace.

```rust
use jsonkit::minify;

fn main() {
    let json = r#"
    {
        "name": "Alice",
        "age": 30
    }
    "#;

    let minified = minify(json);
    println!("{}", minified); // Output: {"name":"Alice","age":30}
}
```

### Format JSON

You can format (prettify) JSON strings using `prettify`.

```rust
use jsonkit::{prettify, IndentStyle};

fn main() {
    let raw_json = r#"{"name":"Alice","age":30,"skills":["Rust","JSON"]}"#;

    // Format with 4 spaces
    match prettify(raw_json, IndentStyle::Spaces(4)) {
        Ok(formatted) => println!("{}", formatted),
        Err(e) => eprintln!("Error formatting JSON: {}", e),
    }
    
    // Format with Tabs
    // let formatted = prettify(raw_json, IndentStyle::Tabs).unwrap();
}
```

### Validate JSON

Check if a string is a valid JSON.

```rust
use jsonkit::validate;

fn main() {
    let valid_json = r#"{"name": "Alice", "age": 30}"#;
    match validate(valid_json) {
        Ok(_) => println!("Valid JSON"),
        Err(e) => println!("Invalid JSON: {}", e),
    }

    let invalid_json = r#"{"name": "Alice", "age": 30,}"#; // Trailing comma
    match validate(invalid_json) {
        Ok(_) => println!("Valid JSON"),
        Err(e) => println!("Invalid JSON: {}", e),
    }
}
```

## 📚 API Reference

### `strip_comments`

```rust
pub fn strip_comments(raw_json_with_comments: &str) -> String
```

Transforms a JSON string containing comments into a standard JSON string.

| Parameter | Type | Description |
| :--- | :--- | :--- |
| `raw_json_with_comments` | `&str` | The input string containing JSONC data. |
| **Returns** | `String` | A new, sanitized string ready for parsing. |

### `minify`

```rust
pub fn minify(json: &str) -> String
```

Minifies a JSON string by removing unnecessary whitespace.

| Parameter | Type | Description |
| :--- | :--- | :--- |
| `json` | `&str` | The input JSON string. |
| **Returns** | `String` | The minified JSON string. |

### `prettify`

```rust
pub fn prettify(raw_json: &str, style: IndentStyle) -> Result<String, String>
```

Prettifies a JSON string with the specified indentation style.

| Parameter | Type | Description |
| :--- | :--- | :--- |
| `raw_json` | `&str` | The input JSON string. |
| `style` | `IndentStyle` | The indentation style (`IndentStyle::Tabs` or `IndentStyle::Spaces(usize)`). |
| **Returns** | `Result<String, String>` | The formatted JSON string or an error message. |

### `validate`

```rust
pub fn validate(json: &str) -> Result<(), String>
```

Validates a JSON string.

| Parameter | Type | Description |
| :--- | :--- | :--- |
| `json` | `&str` | The input JSON string. |
| **Returns** | `Result<(), String>` | `Ok(())` if valid, or an error message. |

### `IndentStyle`

Enum for selecting indentation style.

```rust
pub enum IndentStyle {
    Tabs,
    Spaces(usize),
}
```

## 🛠️ Development

We welcome contributions! To get started with local development:

1. **Clone the repository:**

    ```bash
    git clone https://gitlab.com/lazylib/rs/jsonkit.git
    cd jsonkit
    ```

2. **Run tests:**
    Ensure all functionality works as expected.

    ```bash
    cargo test
    ```

## 📄 License

This project is proudly licensed under the **MIT License**. See the [LICENSE](LICENSE) file for details.

---

Made with ❤️ in Rust.