jsonrustserdeserde-json

How to efficiently extract a portion of JSON as a Vec without intermediate structs?


I have JSON content where, deeply nested, there is an array of numbers I want to extract. I'd like to not create the intermediate structs, so I tried the following:

... get f
let json = serde_json::from_reader::<_, serde_json::Value>(f)?;
let xs: Vec<(f64, f64)> = serde_json::from_value(json["subtree"][0])?;

This complains with

11 | serde_json::from_value(json["subtree"][0])?;
   |                        ^^^^^^^^^^^^^^^^^^^^^ move occurs because value has type `serde_json::value::Value`, which does not implement the `Copy` trait

If I clone, it works fine:

let xs: Vec<(f64, f64)> = serde_json::from_value(json["subtree"][0].clone())?;

But this seems unnecessary. I will not be using the rest of the structure. How do I achieve this without having to create the intermediate structs and without having to clone?


Solution

  • Oh, missed the totally obvious.

    ... get f
    let mut json = serde_json::from_reader::<_, serde_json::Value>(f)?;
    let xs: Vec<(f64, f64)> = serde_json::from_value(json["subtree"][0].take())?;