rust将json字符串直接转为map对象或者hashmap对象

有些时候我们还真的不清楚返回的json数据里面到底有哪些数据,数据类型是什么等,这个时候就可以使用批处理的方式将json字符串转为一个对象,然后通过这个对象的get方法来获取json里面的数据。

rust 复制代码
    pub async fn test_json(&self) {
        let json_str = r#"
            {
                "name": "John",
                "age": 30,
                "city": "New York",
                "info": {
                    "work": "code",
                    "phone": 15670339888,
                    "password": "123456"
                }
            }
        "#;
        let map_obj: Value = serde_json::from_str(json_str).expect("Invalid JSON");
        let name = map_obj.get("name");
        println!("name value is:{name:?}");
        let info = map_obj.get("info");
        let mut phone;
        if info.is_some() {
            phone = info.expect("").get("phone");
            println!("phone number is: {phone:?}");
        }
    }

输出结果:

如果你使用的是reqwest请求库获取到的响应数据,那么你可以直接使用 response.json()方法来解析json数据,并将返回值声明为Value类型,得到的结果就是hashmap对象了:

得到的结果数据:

相关推荐
柠檬丶抒情10 分钟前
Rust深度学习框架Burn 0.20是否能超过python?
python·深度学习·rust·vllm
Vallelonga12 分钟前
浅谈 Rust bindgen 工具
开发语言·rust
木木木一14 分钟前
Rust学习记录--C13 Part1 闭包和迭代器
开发语言·学习·rust
木木木一14 分钟前
Rust学习记录--C13 Part2 闭包和迭代器
开发语言·学习·rust
Vallelonga34 分钟前
Rust 中 extern “C“ 关键字
c语言·开发语言·rust
Watermelo6171 小时前
面向大模型开发:在项目中使用 TOON 的实践与流式处理
javascript·数据结构·人工智能·语言模型·自然语言处理·数据挖掘·json
时光慢煮1 小时前
基于 Flutter × OpenHarmony 开发的 JSON 解析工具实践
flutter·json
wtsolutions19 小时前
Understanding Excel Data Formats - What Excel to JSON Supports
ui·json·excel
wtsolutions1 天前
Real-World Use Cases - How Organizations Use Excel to JSON
json·github·excel