Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Deserialze JSON where one of the fields can be either string or boolean

Cargo.toml

[package]
name = "string-or-bool"
version = "0.1.0"
edition = "2024"

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

Data

{
    "name": "Foo",
    "readme": "README.md"
}
{
    "name": "Bar",
    "readme": false
}

The output

Person { name: "Foo", readme: String("README.md") }
Person { name: "Bar", readme: Bool(false) }

The code

use serde::Deserialize;

#[derive(Deserialize, Debug)]
#[allow(dead_code)]
#[serde(untagged)]
enum Readme {
    Bool(bool),
    String(String),
}

#[derive(Deserialize, Debug)]
#[allow(dead_code)]
struct Person {
    name: String,
    readme: Readme,
}
fn main() {
    let foo_file = "foo.json";
    let content = std::fs::read_to_string(foo_file).unwrap();
    let data = serde_json::from_str::<Person>(&content).unwrap();
    println!("{:?}", data);

    let bar_file = "bar.json";
    let content = std::fs::read_to_string(bar_file).unwrap();
    let data = serde_json::from_str::<Person>(&content).unwrap();
    println!("{:?}", data);
}