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对象了:

得到的结果数据:

相关推荐
wtsolutions34 分钟前
Using the JSON to Excel API - Programmatic Access for Developers
json·excel
wtsolutions4 小时前
Understanding JSON Formats - What JSON to Excel Supports
json·excel
wtsolutions4 小时前
Advanced Features - Unlocking the Power of JSON to Excel Pro
linux·json·excel
wtsolutions7 小时前
Real-World Use Cases - How Organizations Use JSON to Excel
json·excel
wtsolutions7 小时前
Introduction to JSON to Excel - The Ultimate Conversion Tool
json·excel
盛者无名8 小时前
Rust的所有权(Owenership)
开发语言·rust
San30.8 小时前
LangChain 第二课:拒绝“废话”,用 Zod 强制 AI 输出标准 JSON
人工智能·langchain·json
wtsolutions8 小时前
JSON to Excel WPS Add-in - Perfect for WPS Office Users
json·excel·wps
BlockChain8889 小时前
MPC 钱包实战(三):Rust MPC Node + Java 调度层 + ETH 实际转账(可运行)
java·开发语言·rust
wtsolutions10 小时前
Flat vs Nested JSON Conversion - Deep Dive into Conversion Modes
json