Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/lucidfrontier45/serdeio
Tiny IO utility library for Rust to serialize/deserialize Serde compatible structs
https://github.com/lucidfrontier45/serdeio
file-io file-reading file-writing input-output io rust serde serialization
Last synced: about 1 month ago
JSON representation
Tiny IO utility library for Rust to serialize/deserialize Serde compatible structs
- Host: GitHub
- URL: https://github.com/lucidfrontier45/serdeio
- Owner: lucidfrontier45
- License: mit
- Created: 2023-09-28T12:07:59.000Z (about 1 year ago)
- Default Branch: develop
- Last Pushed: 2024-07-01T00:35:30.000Z (6 months ago)
- Last Synced: 2024-10-31T11:50:00.152Z (about 2 months ago)
- Topics: file-io, file-reading, file-writing, input-output, io, rust, serde, serialization
- Language: Rust
- Homepage: https://crates.io/crates/serdeio
- Size: 27.3 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# SerdeIO
Tiny IO utility library for Rust to serialize/deserialize Serde compatible structs# Install
```sh
cargo add serdeio
```SerdeIO supports JSON and JSON Lines formats. Additional formats are supported by enabling corresponding features.
- `yaml`
- `csv`# How to use
- `read_record_from_reader` is used to read a deserializable type `T` from `std::io::Read`. Data format must be specified by `DataFormat` enum.
- `read_records_from_reader` always tries to deserialize the data as `Vec`.
- `read_record_from_file` accepts an `AsRef`. Data format is automatically determined by file extension.
- `write_*` functions follow the same rules as `read_*`.Note that some data format like CSV and JSON Lines support only reading records `Vec`.
# Examples
The following code read a JSON file and parse it as `Vec`. Then it encodes the data into YAML format and write it to STDOUT.
```rust
use anyhow::{anyhow, Context, Result as AnyResult};
use serde::{Deserialize, Serialize};
use serdeio::{read_record_from_file, write_records_to_writer, DataFormat};#[derive(Debug, Deserialize, Serialize)]
struct User {
id: u32,
name: String,
items: Vec,
}pub fn main() -> AnyResult<()> {
// get input file path from argv
let args: Vec = std::env::args().collect();
let input_file_path = &args[1];// read json file to memory
let users: Vec = read_record_from_file(input_file_path)
.context("Failed to read records from file")?;// write to stdout in json lines format
let writer = std::io::stdout();
write_records_to_writer(writer, DataFormat::JsonLines, &users).unwrap();Ok(())
}
```