簡體   English   中英

使用 rust 從字節中獲取 json 值

[英]Get json value from byte using rust

我需要從base64值中獲取名稱,我嘗試如下,但我無法解析它並獲取 name 屬性,知道我該怎么做嗎?

extern crate base64;
use serde_json::Value;
fn main() {


    let v = "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ";

    let bytes = base64::decode(v).unwrap();
    println!("{:?}", bytes);
   
   
    let v: Value = serde_json::from_slice(bytes);
    

}

該值表示 json 喜歡

{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1df0f644a139f8d526a44af8abf78e8e

最后我需要打印"name": "John Doe"

這是解碼后的值

在此處輸入圖片說明

Masklinn 解釋了為什么你有錯誤,你應該閱讀他的回答。

但 IMO 最簡單和最安全的解決方案是使用serde 的導出來解碼為所需的結構:

use serde::Deserialize;

/// a struct into which to decode the thing
#[derive(Deserialize)]
struct Thing {
    name: String,
    // add the other fields if you need them
}

fn main() {
    let v = "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ";
    let bytes = base64::decode(v).unwrap(); // you should handle errors
    let thing: Thing = serde_json::from_slice(&bytes).unwrap();
    let name = thing.name;
    dbg!(name);
}

Denys 提供了使用 serde 的常用方法,如果這是一個選項(如果文檔不是動態的),您絕對應該應用他們的解決方案。

然而:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1df0f644a139f8d526a44af8abf78e8e

您是否考慮過至少遵循編譯器的指示? 銹病編譯器是既俏麗表現和非常嚴格的,如果你放棄了在每一個編譯錯誤,甚至沒有試圖了解發生了什么happenig,你將有一個非常困難時期。

如果您嘗試編譯代碼段,它會告訴您的第一件事是

error[E0308]: mismatched types
  --> src/main.rs:12:43
   |
12 |     let v: Value = serde_json::from_slice(bytes);
   |                                           ^^^^^
   |                                           |
   |                                           expected `&[u8]`, found struct `Vec`
   |                                           help: consider borrowing here: `&bytes`
   |
   = note: expected reference `&[u8]`
                 found struct `Vec<u8>`

雖然它並不總是完美運行,但編譯器的建議是正確的: base64必須為返回值分配空間,以便它產生一個Vec ,但serde_json並不真正關心數據來自哪里,所以它需要一個片。 僅引用 vec 就允許 rustc 將其強制為切片。

第二個建議是:

error[E0308]: mismatched types
  --> src/main.rs:12:20
   |
12 |     let v: Value = serde_json::from_slice(bytes);
   |            -----   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected enum `Value`, found enum `Result`
   |            |
   |            expected due to this
   |
   = note: expected enum `Value`
              found enum `Result<_, serde_json::Error>`

這不提供解決方案,但簡單的unwrap可以用於測試。

這會產生一個適當的serde_json::value::Value ,您可以以正常方式操作,例如

v.get("name").and_then(Value::as_str));

如果鍵丟失或未映射到字符串,則返回值NoneOption<&str> ,如果鍵存在並映射到字符串,則返回Some(s)https : //play.rust-lang.org/ ?version=stable&mode=debug&edition=2018&gist=5025d399644694b4b651c4ff1b9125a1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM