Since you mentioned in your question that you don't actually need the rest of the JSON data, maybe the Struson library and its seek_to
method could be helpful for this. It allows positioning the JSON reader at the specified path, skipping all other values. This will likely be more efficient memory-wise than having to deserialize the complete JSON data as Value
first before obtaining the relevant deeply nested portion.
You could then use Struson's JsonReader
method begin_array
to start the enclosing JSON array and then use within that begin_array
, end_array
and next_number
to read the (f64, f64)
values (assuming they look like [1.2, 3.4]
in JSON).
// Assumes this is roughly the structure of your JSON data
let json = r#"
{
"subtree": [
[
[1.2, 3.4],
[-4.5, 6]
]
]
}
"#;
// `std::io::Read` providing the JSON data; in this example the str bytes
let reader = json.as_bytes();
let mut xs: Vec<(f64, f64)> = Vec::new();
let mut json_reader = JsonStreamReader::new(reader);
json_reader.seek_to(&json_path!["subtree", 0])?;
json_reader.begin_array()?;
while json_reader.has_next()? {
// Read the (f64, f64) values
json_reader.begin_array()?;
xs.push((
json_reader.next_number()??,
json_reader.next_number()??
));
json_reader.end_array()?;
}
// Optionally consume the remainder of the JSON document
json_reader.skip_to_top_level()?;
json_reader.consume_trailing_whitespace()?;
println!("xs: {xs:?}");
Alternatively if you really wanted to use Serde-like functionality to deserialize the Vec<(f64, f64)>
, you could use the serde
feature instead:
let json = r#"
{
"subtree": [
[
[1.2, 3.4],
[-4.5, 6]
]
]
}
"#;
// `std::io::Read` providing the JSON data; in this example the str bytes
let reader = json.as_bytes();
let mut json_reader = JsonStreamReader::new(reader);
json_reader.seek_to(&json_path!["subtree", 0])?;
// Uses Serde's Deserialize implementation
let xs: Vec<(f64, f64)> = json_reader.deserialize_next()?;
// Optionally consume the remainder of the JSON document
json_reader.skip_to_top_level()?;
json_reader.consume_trailing_whitespace()?;
println!("xs: {xs:?}");
Disclaimer: I am the author of Struson, and currently it is still experimental (but feedback is highly appreciated!).