如何将 `serde_json::Value` 转换为列表或 `Vec<_>`?

huangapple go评论72阅读模式
英文:

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

问题

Here is the translated code snippet:

use std::fs::File;
use std::io::Read;

use serde_json::Value;
use crate::scene_builder::SceneBuilder;

fn json_hello_world() {
    // 一些 JSON 输入数据作为 &str。也许这来自用户。
    let data = r#"
        {
            "name": "John Doe",
            "age": 43,
            "phones": [
                "+44 1234567",
                "+44 2345678"
            ]
        }"#;

    // 将数据字符串解析为 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());
    // 编译错误:在 `Value` 中找不到方法(.size())
}

fn main() {
    json_hello_world();
}

Note: I've removed the HTML entities (e.g., &quot;) and replaced them with regular double quotes in the translated code.

英文:

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 &amp;str. Maybe this comes from the user.
    let data = r#&quot;
        {
            &quot;name&quot;: &quot;John Doe&quot;,
            &quot;age&quot;: 43,
            &quot;phones&quot;: [
                &quot;+44 1234567&quot;,
                &quot;+44 2345678&quot;
            ]
        }&quot;#;

    // Parse the string of data into serde_json::Value.
    let value: Value = serde_json::from_str(data).unwrap();
    let phones = &amp;value[&quot;phones&quot;];
    println!(&quot;phone[0]: {}&quot;, phones[0]);
    //println!(&quot;number of phones: {}&quot;, 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!(&quot;phone[0]: {}&quot;, phones[0]);

But how do I convert such a serde_json::Value into a list or Vec&lt;Value&gt; so I can access its size/length, like let phones: Vec&lt;Value&gt; = value[&quot;phones&quot;]; or let size = phones.size();?

答案1

得分: 1

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());
英文:

You can use as_array():

println!(&quot;number of phones: {}&quot;, 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&lt;String&gt;,
}

let value: Data = serde_json::from_str(data).unwrap();
let phones = &amp;value.phones;
println!(&quot;phone[0]: {}&quot;, phones[0]);
println!(&quot;number of phones: {}&quot;, phones.len());

答案2

得分: 0

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.");
}
英文:
let phones = value[&quot;phones&quot;].as_array();

    if let Some(phones) = phones {
        println!(&quot;phone[0]: {}&quot;, phones[0]);

        let size = phones.len();
        println!(&quot;number of phones: {}&quot;, size);
    } else {
        println!(&quot;Invalid JSON structure: &#39;phones&#39; is not an array.&quot;);
    }

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.

huangapple
  • 本文由 发表于 2023年5月25日 22:22:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76333345.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定