Skip to content

mwanjajoel/rust-json-formatter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

JSON Formatter

A fast and reliable command-line tool written in Rust for formatting, validating, and pretty-printing JSON files.

Table of Contents

Features

  • 📄 Read JSON files - Read JSON from files or standard input
  • Validate JSON - Ensure JSON syntax is correct before formatting
  • 🎨 Pretty print - Format JSON with consistent indentation and spacing
  • 🚀 Fast performance - Built with Rust for optimal speed
  • 🔧 Flexible input - Support for file paths and stdin
  • 📤 Flexible output - Output formatted JSON to stdout
  • 🛡️ Error handling - Clear error messages for invalid JSON

For Users

Installation

Install from crates.io (Recommended)

The easiest way to install json-formatter is using cargo install:

cargo install json-formatter-cli

This will download, compile, and install the binary to ~/.cargo/bin/json-formatter. Make sure ~/.cargo/bin is in your PATH environment variable.

Note: You need to have Rust installed (version 1.70 or later) to use cargo install.

Verify Installation

After installation, verify that the tool is working:

json-formatter --version

You should see the version number printed.

Usage

Basic Usage

Format a JSON file:

json-formatter input.json

This will read input.json, validate it, and print the formatted JSON to stdout.

Read from Standard Input

Pipe JSON content:

cat input.json | json-formatter
# or
echo '{"key":"value"}' | json-formatter

Command-Line Options

USAGE:
    json-formatter [OPTIONS] [FILE]

ARGS:
    <FILE>    Input JSON file (if not provided, reads from stdin)

OPTIONS:
    --minify              Minify the JSON output (compact format)
    -h, --help            Print help information
    -V, --version         Print version information

Examples

Example 1: Format a JSON file

Input file (data.json):

{"name":"John Doe","age":30,"city":"New York","hobbies":["reading","coding","traveling"]}

Command:

json-formatter data.json

Output:

{
  "name": "John Doe",
  "age": 30,
  "city": "New York",
  "hobbies": [
    "reading",
    "coding",
    "traveling"
  ]
}

Example 2: Minify JSON output

json-formatter data.json --minify

This will output compact JSON without any whitespace.

Example 3: Pipe JSON from another command

curl -s https://api.example.com/data.json | json-formatter

Example 4: Validate JSON without formatting

The tool will automatically validate JSON and exit with an error code if the JSON is invalid:

json-formatter invalid.json
# Error: Invalid JSON: expected value at line 1 column 1

Error Handling

The tool provides clear error messages for common issues:

  • File not found: Error: Failed to read file: No such file or directory
  • Invalid JSON: Error: Invalid JSON: <detailed error message>
  • Permission denied: Error: Failed to read file: Permission denied
  • Read error: Error: Failed to read file: <error details>

Exit codes:

  • 0 - Success
  • 1 - General error (invalid JSON, file error, etc.)

Troubleshooting

Common Issues

Issue: command not found: json-formatter

  • Solution: Make sure ~/.cargo/bin is in your PATH. You can add it by running:
    export PATH="$HOME/.cargo/bin:$PATH"
    Add this line to your ~/.bashrc, ~/.zshrc, or equivalent shell configuration file to make it permanent.

Issue: Permission denied

  • Solution: Ensure you have read permissions for input files.

Issue: Invalid JSON error

  • Solution: Verify your JSON file is valid. You can use online JSON validators to check the syntax.

For Developers

This section is for developers who want to contribute to the project, build from source, or understand the codebase.

Prerequisites

  • Rust (version 1.70 or later)
  • cargo (comes with Rust)

Building from Source

  1. Clone the repository:

    git clone https://github.com/mwanjajoel/rust-json-formatter.git
    cd rust-json-formatter
  2. Build the project:

    cargo build --release
  3. The binary will be available at target/release/json-formatter

  4. (Optional) Install locally:

    cargo install --path .

Development Workflow

When developing or testing, you can use cargo run instead of building the binary first:

Format Sample JSON Files

The project includes sample JSON files in the data/ folder for testing:

# Format simple.json
cargo run -- data/simple.json

# Format nested.json
cargo run -- data/nested.json

# Format complex.json
cargo run -- data/complex.json

Format with Options

# Minify JSON (compact output)
cargo run -- data/nested.json --minify

Read from stdin

# Pipe JSON content
cat data/simple.json | cargo run --

# Echo JSON and format
echo '{"key":"value","number":42}' | cargo run --

Running Tests

Run the test suite:

cargo test

Run tests with output:

cargo test -- --nocapture

Project Structure

json-formatter/
├── Cargo.toml          # Project configuration and dependencies
├── Cargo.lock          # Locked dependency versions
├── README.md           # This file
├── src/
│   └── main.rs         # Main application code
└── data/               # Sample JSON files for testing
    ├── simple.json
    ├── nested.json
    └── complex.json

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

Contribution Guidelines

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Add tests if applicable
  5. Ensure all tests pass (cargo test)
  6. Ensure the code compiles without warnings (cargo build)
  7. Commit your changes (git commit -m 'Add some amazing feature')
  8. Push to the branch (git push origin feature/amazing-feature)
  9. Open a Pull Request

Code Style

  • Follow Rust's official style guide
  • Run cargo fmt to format your code
  • Run cargo clippy to check for common issues

Additional Information

Dependencies

  • clap - Command-line argument parsing
  • serde - Serialization framework
  • serde_json - JSON serialization/deserialization

Performance

JSON Formatter is built with Rust for optimal performance:

  • Fast parsing and serialization
  • Low memory footprint
  • Efficient file I/O operations

Benchmark results (on typical JSON files):

  • Small files (< 1KB): < 1ms
  • Medium files (1KB - 100KB): < 10ms
  • Large files (100KB - 1MB): < 100ms

Roadmap

Future enhancements may include:

  • Support for JSON5 format
  • Output to file option (-o, --output)
  • Custom indentation size (-i, --indent)
  • Custom sorting of object keys
  • Colorized output for terminals
  • Batch processing of multiple files
  • JSON schema validation
  • Support for JSON streaming

License

This project is licensed under the MIT License - see the LICENSE file for details.


Note: This tool is designed to be simple, fast, and reliable. It focuses on the core functionality of formatting and validating JSON without unnecessary complexity.

About

A fast JSON formatter written in Rust

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages