• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Building a Simple Rust CLI Tool to Parse JSON Files

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
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

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"

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"
}

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);
}
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

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
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.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

— just $5.

If this was helpful, you can also support me here:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

☕


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу