json-result

Crates.iojson-result
lib.rsjson-result
version0.1.1
created_at2025-12-03 15:12:44.685304+00
updated_at2025-12-07 06:07:16.255504+00
descriptionA generic enum representing a JSON result that can either be a success (`Ok`) with a value of type `T` or an error (`Err`) with a value of type `E`.
homepagehttps://github.com/LorenzoLeonardo/json-result
repositoryhttps://github.com/LorenzoLeonardo/json-result
max_upload_size
id1964219
size36,592
Lorenzo Leonardo (LorenzoLeonardo)

documentation

https://docs.rs/json-result

README

JsonResult

JsonResult is a Rust generic enum designed for seamlessly handling JSON values that can represent either a success (Ok) or error (Err) result, with flexible types. It integrates tightly with Serde for serialization and deserialization.

Latest Version License Documentation Build Status Downloads

Features

  • Supports untagged enum representation for natural JSON parsing.
  • Converts to and from serde_json::Value easily.
  • Provides detailed error messages when deserialization fails.
  • Generic over success (T) and error (E) types.

Installation

Add this to your Cargo.toml:

[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

Usage

use serde_json::json;
use std::convert::TryFrom;

let success_json = json!({"id": 1, "name": "Alice"});
let error_json = json!({"error_code": 404, "message": "Not Found"});

// Define your success and error types
#[derive(serde::Deserialize, serde::Serialize, Debug)]
struct User {
    id: u32,
    name: String,
}

#[derive(serde::Deserialize, serde::Serialize, Debug)]
struct ApiError {
    error_code: u16,
    message: String,
}

type MyJsonResult = JsonResult<User, ApiError>;

// Deserialize JSON into JsonResult
let res_ok: MyJsonResult = success_json.try_into().unwrap();
let res_err: MyJsonResult = error_json.try_into().unwrap();

match res_ok {
    JsonResult::Ok(user) => println!("User: {:?}", user),
    JsonResult::Err(e) => println!("Error: {:?}", e),
}

match res_err {
    JsonResult::Ok(user) => println!("User: {:?}", user),
    JsonResult::Err(e) => println!("Error: {:?}", e),
}

// Convert JsonResult back to serde_json::Value
let json_val: serde_json::Value = res_ok.into();
println!("Serialized back to JSON: {}", json_val);
Commit count: 0

cargo fmt