1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Rust】serde_jsonを使ってjsonから一部の項目だけ取得する

Posted at

概要

Rustでjsonを読み込む際は、RustでJSONを読み込みVecにデシリアライズするの記事にある通り、デシリアライズ対象のstructを用意した上で、serde_jsonを使って変換するという流れになると思います。
ただ、外部のAPIから情報を取得するときなど、レスポンスの全項目は不要というケースもあるかなと思い、その場合はstructを用意せず、対象の項目だけ取得できれば十分な時もあります。今回はserde_json`を使ってjson中の一部項目だけ取得する方法を紹介します。

対応方法

serde_jsonのReadMeのOperating on untyped JSON valuesの項にある通り、jsonを一旦serde_json::Valueで読み込むことで、指定した項目を取得できます。

実装サンプル

実装サンプルとして、以下のサンプルのjsonからresultsのidのみを抽出します。

sample.json
{
  "count": 2,
  "results": [
    { "id": "id1", "name": "name1" },
    { "id": "id2", "name": "name2" },
    { "id": "id3", "name": "name3" }
  ]
}
sample.rs
pub fn sample_method(json: String) -> Result<Vec<String>, Box<dyn Error>> {
    let mut result_vec: Vec<String> = Vec::new();
    let v: serde_json::Value = serde_json::from_str(&json)?;

    let empty_vec: Vec<serde_json::Value> = Vec::new();
    // resultsの配列を取得
    let results = v["results"].as_array().unwrap_or_else(|| &empty_vec);
    for r in results {
        // jsonからidを取得
        let id = r["id"].as_str().unwrap();
        // 結果をVecに追加
        result_vec.push(id.to_string());
    }
    return Ok(result_vec);
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?