Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert `serde_json::Value` into a list or a Vec<_>?

Tags:

json

rust

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();?

like image 895
Rahn Avatar asked Oct 15 '25 19:10

Rahn


2 Answers

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());
like image 155
Chayim Friedman Avatar answered Oct 18 '25 13:10

Chayim Friedman


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.

like image 38
99problems Avatar answered Oct 18 '25 11:10

99problems