Json: How to extract array from a json and iterate?

Created on 7 Jan 2019  路  2Comments  路  Source: serde-rs/json

I have a json string as

{
  "models": [
    {
      "id": 1011880,
      "quantity": "6.118954",
      "price": "409.78",
      "taker_side": "sell",
      "created_at": 1457370745
    },
    {
      "id": 1011791,
      "quantity": "1.15",
      "price": "409.12",
      "taker_side": "sell",
      "created_at": 1457365585
    }
  ],
  "current_page": 2,
  "total_pages": 1686
}

Without defining the whole structure like current_page and total_pages. Can I get the content which is an Array from models and do into_iter() with it?

support

Most helpful comment

Yes, you can define the parts you need.

use serde_derive::Deserialize;

#[derive(Deserialize)]
struct Response {
    models: Vec<Model>,
}

#[derive(Deserialize)]
struct Model {
    id: u64,
}

fn main() -> serde_json::Result<()> {
    let j = r#"
        {
          "models": [
            {
              "id": 1011880,
              "quantity": "6.118954",
              "price": "409.78",
              "taker_side": "sell",
              "created_at": 1457370745
            },
            {
              "id": 1011791,
              "quantity": "1.15",
              "price": "409.12",
              "taker_side": "sell",
              "created_at": 1457365585
            }
          ],
          "current_page": 2,
          "total_pages": 1686
        }"#;

    let resp: Response = serde_json::from_str(j)?;
    for model in resp.models {
        println!("id={}", model.id);
    }
    Ok(())
}

All 2 comments

Yes, you can define the parts you need.

use serde_derive::Deserialize;

#[derive(Deserialize)]
struct Response {
    models: Vec<Model>,
}

#[derive(Deserialize)]
struct Model {
    id: u64,
}

fn main() -> serde_json::Result<()> {
    let j = r#"
        {
          "models": [
            {
              "id": 1011880,
              "quantity": "6.118954",
              "price": "409.78",
              "taker_side": "sell",
              "created_at": 1457370745
            },
            {
              "id": 1011791,
              "quantity": "1.15",
              "price": "409.12",
              "taker_side": "sell",
              "created_at": 1457365585
            }
          ],
          "current_page": 2,
          "total_pages": 1686
        }"#;

    let resp: Response = serde_json::from_str(j)?;
    for model in resp.models {
        println!("id={}", model.id);
    }
    Ok(())
}

Thank you!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mfarrugi picture mfarrugi  路  4Comments

lilith picture lilith  路  4Comments

VictorKoenders picture VictorKoenders  路  6Comments

dtolnay picture dtolnay  路  6Comments

brundonsmith picture brundonsmith  路  3Comments