So I can read a json file with serde_json
:
use std::fs::File;
use std::io::Read;
use serde_json::Value;
use crate::scene_builder::SceneBuilder;
fn json_hello_world() {
// Some JSON input data as a &str. Maybe this comes from the user.
let data = r#"
{
"name": "John Doe",
"age": 43,
"phones": [
"+44 1234567",
"+44 2345678"
]
}"#;
// Parse the string of data into serde_json::Value.
let value: Value = serde_json::from_str(data).unwrap();
let phones = &value["phones"];
println!("phone[0]: {}", phones[0]);
//println!("number of phones: {}", phones.size());
// compilation error: method (.size()) not found in `Value`
}
fn main() {
json_hello_world();
}
and print out value of a list element with correct index: println!("phone[0]: {}", phones[0]);
But how do I convert such a serde_json::Value
into a list or Vec<Value>
so I can access its size/length, like let phones: Vec<Value> = value["phones"];
or let size = phones.size();
?
2
Answers
You can use
as_array()
:But the right thing to do is to deserialize into a typed struct:
The
as_array
method returns anOption
because the value may not be an array. In case the value is not an array, the method will returnNone
, and you can handle that condition accordingly.