DEV Community

Cover image for Building a Simple Rust CLI Tool to Parse JSON Files
HexShift
HexShift

Posted on

1

Building a Simple Rust CLI Tool to Parse JSON Files

When working with JSON files, it’s common to perform transformations, extract specific data, or perform aggregations. Rust’s excellent performance and strong typing make it a great choice for processing JSON data efficiently. In this tutorial, we’ll build a simple CLI tool in Rust that reads a JSON file, parses it, and prints a specific field from the data.


Step 1: Set Up Your Project

Let’s begin by creating a new Rust project:

cargo new json_parser --bin
cd json_parser
Enter fullscreen mode Exit fullscreen mode

This sets up a new Rust project with the src/main.rs file for our code.


Step 2: Add Dependencies for JSON Parsing

We’ll use the serde and serde_json crates to handle JSON parsing. Add them to your Cargo.toml:

[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
Enter fullscreen mode Exit fullscreen mode

These crates make it easy to work with JSON in a structured way.


Step 3: Parse the JSON File

Now, let’s write the code to parse a JSON file and print out a specific field. For this example, assume the JSON file looks like this:

{
  "name": "John Doe",
  "age": 30,
  "email": "john.doe@example.com"
}
Enter fullscreen mode Exit fullscreen mode

Here’s the code for main.rs:

use serde::Deserialize;
use std::env;
use std::fs::File;
use std::process;

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

fn main() {
    let args: Vec = env::args().collect();

    if args.len() < 2 {
        eprintln!("Usage: json_parser ");
        process::exit(1);
    }

    let filename = &args[1];
    let file = File::open(filename).unwrap_or_else(|_| {
        eprintln!("Could not open file {}", filename);
        process::exit(1);
    });

    let person: Person = serde_json::from_reader(file).unwrap_or_else(|_| {
        eprintln!("Error parsing JSON in file {}", filename);
        process::exit(1);
    });

    println!("Name: {}", person.name);
    println!("Age: {}", person.age);
    println!("Email: {}", person.email);
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Build and Test the Tool

Now, build and run your tool with a sample JSON file:

cargo build --release
./target/release/json_parser person.json
Enter fullscreen mode Exit fullscreen mode

If successful, the tool will print the contents of the JSON file in a readable format:

Name: John Doe
Age: 30
Email: john.doe@example.com
Enter fullscreen mode Exit fullscreen mode

Use Case Scenario

Imagine you’re building an admin dashboard that handles user data. You could use this Rust CLI tool to automate tasks like extracting user information from configuration files, generating reports, or processing large datasets. This tool can be expanded to include more complex filtering or transformation logic, giving you a fast and reliable utility for handling your data in a structured way.


✅ Pros and ❌ Cons of Using Rust for CLI Tools

✅ Pros:

  • ⚡ Rust is extremely fast for processing large files and datasets.
  • 📦 Excellent support for data serialization/deserialization with serde.
  • 🔐 Strong type safety ensures data integrity and catches errors early.
  • 🧪 Integration with test frameworks makes it easy to write unit tests.

❌ Cons:

  • 📘 Requires some upfront learning for newcomers to Rust.
  • ⏱ Longer compilation times on larger projects.
  • 🧱 Some libraries or tools in the ecosystem may be less mature than in other languages.

Summary

You’ve now created a Rust CLI tool for parsing JSON files! This demonstrates how Rust can help you build tools that handle structured data quickly and safely. By leveraging the power of serde and serde_json, you can easily extend this tool to handle more complex JSON structures or add additional features like writing transformed data back to a file.

If you’d like to learn more and take your Rust CLI skills to the next level, check out my 15-page PDF guide, which walks you through the entire process of building fast and reliable command-line utilities in Rust.

Crafting Command-Line Tools in Rust: A Practical Guide to Building Fast, Reliable Utilities — just $5.


If this was helpful, you can also support me here: Buy Me a Coffee

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

ACI image

ACI.dev: Fully Open-source AI Agent Tool-Use Infra (Composio Alternative)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Check out our GitHub!

👋 Kindness is contagious

Dive into this insightful write-up, celebrated within the collaborative DEV Community. Developers at any stage are invited to contribute and elevate our shared skills.

A simple "thank you" can boost someone’s spirits—leave your kudos in the comments!

On DEV, exchanging ideas fuels progress and deepens our connections. If this post helped you, a brief note of thanks goes a long way.

Okay