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();
?
You can use as_array()
:
println!("number of phones: {}", phones.as_array().unwrap().len());
But the right thing to do is to deserialize into a typed struct:
#[derive(serde::Deserialize)]
struct Data {
name: String,
age: u32,
phones: Vec<String>,
}
let value: Data = serde_json::from_str(data).unwrap();
let phones = &value.phones;
println!("phone[0]: {}", phones[0]);
println!("number of phones: {}", phones.len());
let phones = value["phones"].as_array();
if let Some(phones) = phones {
println!("phone[0]: {}", phones[0]);
let size = phones.len();
println!("number of phones: {}", size);
} else {
println!("Invalid JSON structure: 'phones' is not an array.");
}
The as_array
method returns an Option
because the value may not be an array. In case the value is not an array, the method will return None
, and you can handle that condition accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With