Reading multiple files based on a partial name?

but how then do i define fields inside fields?
like this json has { archive: { stats: } }
i know how to define "flat" structs, just not nested ones?

GitHub - serde-rs/json: Strongly typed JSON library for Rust this one shows fields, but i have {} fields?

You just have to nest structs:

#[derive(serde::Deserialize)]
struct A {
    b: B,
}

#[derive(serde::Deserialize)]
struct B {
    foo: String,
}
1 Like

thank you again :slight_smile:
that leads me to this: #[derive(serde::Deserialize)]struct StructArchive { commandline: Vec<Stri - Pastebin.com
thats correct then? I tried giving them meaningfull names :slight_smile:

ahh, i found this: https://transform.tools/json-to-rust-serde
makes life much easier :slight_smile:

You should remove the prefix Struct from all your structs. It doesn't mean anything. The name Json for your own struct which doesn't deal with JSON, is probably not the best choice, what does that JSON object means or where it comes from is probably a better name. The struct doesn't care it originated from JSON.

2 Likes

actually, with the transform url i added all the names got changed :slight_smile: the struct is now called Root.

...
let stream = Deserializer::from_str(&file_content).into_iter::<Root>();
        for value in stream {
            // this prints out the json as before
            println!("{:?}",value);
           // but i still seem to be unable to access anything inside value.  
        }
...

Are you sure that print doesn't show your JSON value wrapped in a Ok variant of a Result ?

You should show the error messages emitted by the compiler.

print does indeed return an ok :slight_smile:
so i would think i could use

match result {
    Ok(val) => {
        // Use val here....
    },
    Err(err) => {
        // Do something with the error if you want
    }
}

correct?

Yes, or unwrap or the ? operator

1 Like

i fixed it like so:

            match value {
                Ok(val) => {
                    // We have data, do something with it
                    let r = json!(val);
                    let c = &r["archive"]["stats"]["compressed_size"];
                    println!("{}", c);

                },
                Err(err) => {
                    // Something went wrong, print an error!
                    println!("Error: {} while trying to read json from {}", err, &file_content);
                }

Why are you re-wrapping it in JSON ? (The json! macro) You've deserialized it, just use the struct fields.

2 Likes

because that seems to be the only way i can access the data? Ive spend today Googling my *ss off and this is the best i could do :slight_smile:

OMG!
so without using json!() i can access the data like so:
println!("{:?}", val.archive.command_line);

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.