I am struggling to use clap's derive syntax to define an argument that takes a JSON array as a value and parses it into a Vec
Here's how I want to pass the argument in my CLI:
myapp --my-structs '[{"name":"josh"}, {"name:"shelly"}]'
My desired result would be like:
args == Args {
my_structs: [
MyStruct { name: "josh" },
MyStruct { name: "shelly" },
]
}
Here's my code:
use clap::{Command, CommandFactory, Parser, ValueHint};
use serde::Deserialize;
use std::str::FromStr;
#[derive(Deserialize)]
struct MyStruct {
name: String,
}
impl FromStr for MyStruct {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let res: MyStruct =
serde_json::from_str(s).map_err(|e| format!("error parsing my struct: {}", e))?;
Ok(res)
}
}
#[derive(Parser, Debug)]
pub struct Args {
#[arg(
long,
value_name = "MY_STRUCTS",
help = "an array of MyStructs",
)]
my_structs: Vec<MyStruct>
}
// The primary function that runs the program
pub fn run() {
let mut args: Args = Args::parse();
}
The error i get says:
error: invalid value '[{"name":"josh"},{"name":"shelly"}]' for '--error-rules <ERROR_RULES>': error parsing my struct: invalid type: map, expected a string at line 1 column 1
Thanks so much in advance to any clap veterans who can point me in the right direction!