2D vector extraction from json

What is the proper way to parse Vec<Vec<>> from json ? Example:

use serde_json::json;


fn main() {

   let s = json!({
       
       "name" : "Toxic",
       "keys" : [[203,11,67,91,247,224,121,244,100,137,114],[171,183,245,237,156,95,68,66,146,19,238,56,220,152,48],[54,194,197,110,9,237,50,62,190,33,14,161,170],[170,25,119,111,42,153,130,77,196,61,22]]
   });
   let a : Vec<Vec<u8>> = serde_json::ser::to_vec(&s["keys"].as_object()).unwrap();
   
   println!("{:?}", a);
    
}

Error:

error[E0308]: mismatched types
  --> src/main.rs:11:27
   |
11 |    let a : Vec<Vec<u8>> = serde_json::ser::to_vec(&s["keys"].as_object()).unwrap();
   |                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::vec::Vec`, found u8
   |
   = note: expected type `std::vec::Vec<std::vec::Vec<u8>>`
              found type `std::vec::Vec<u8>`

to_vec is not for parsing, but for generating a string of JSON (the syntax) and putting it in a Vec. It's JSON.stringify() equivalent. It just happens to look vaguely like the type you want to parse to, but that's a coincidence.

Use from_value that can make any type. Output type won't be in function's name.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.