How to convert Base64 to a JSON string in Rust

1 Answer

0 votes
use base64::engine::general_purpose;
use base64::Engine;
use serde_json::Value;

fn base64_to_pretty_json(base64_string: &str) -> Result<String, String> {
    // Decode Base64 to plain text using the STANDARD engine
    match general_purpose::STANDARD.decode(base64_string) {
        Ok(decoded_bytes) => {
            let decoded_string = String::from_utf8(decoded_bytes)
                .map_err(|_| "Invalid UTF-8 sequence".to_string())?;

            // Parse plain text to JSON
            match serde_json::from_str::<Value>(&decoded_string) {
                Ok(json_object) => {
                    // Convert JSON object to pretty JSON string
                    let json_string =
                        serde_json::to_string_pretty(&json_object).map_err(|e| e.to_string())?;
                    Ok(json_string)
                }
                Err(e) => Err(format!("Error parsing JSON: {}", e)),
            }
        }
        Err(e) => Err(format!("Error decoding Base64: {}", e)),
    }
}

fn main() {
    let base64_string = "ewogICJ1c2VybmFtZSI6ICJPa2FiZSIsCiAgImFnZSI6IDM3Cn0=";

    match base64_to_pretty_json(base64_string) {
        Ok(json_string) => println!("JSON String:\n{}", json_string),
        Err(err) => eprintln!("{}", err),
    }
}



/*
run:

JSON String:
{
  "age": 37,
  "username": "Okabe"
}

*/

 



answered Dec 8, 2025 by avibootz
edited Dec 8, 2025 by avibootz
...