Parsing an object inside an object with serde_json
Asked Answered
E

1

6

I am stuck, below is the JSON which I am receiving:

{
   "BCH": {
      "aclass": "currency",
      "altname": "BCH",
      "decimals": 10,
      "display_decimals": 5
   }
}

I am bit confused on how my struct should look like to parse the attributes using theserde_json crate. Below is what I currently have:

#[derive(Deserialize, Debug)]
struct Assets  {  
    aclass: String,
    altname: String,
    decimals: u8,
    display_decimals: u8,
}

#[derive(Deserialize, Debug)]
struct Currency {
    assest: Assets,
}


fn to_assets_type(value: serde_json::Value) -> Currency {
 serde_json::from_value(value).unwrap()
}

I am getting an error message:

thread 'main' panicked at 'called Result::unwrap() on an Err value: ErrorImpl { code: Message("missing field assest"), line: 0, column: 0 }', src/libcore/result.rs:860:4

Estevez answered 6/9, 2017 at 11:44 Comment(3)
Looks like your json is an object inside an object ....Aerialist
I cannot test my intuition now, but I think you should try to rename your Currency asset field to BCH.Consult
BCH is not staticEstevez
H
9

I think you want a HashMap.

#[macro_use] extern crate serde;
extern crate serde_json;

use std::collections::HashMap;

static VALUE: &str = r#"{
   "BCH": {
      "aclass": "currency",
      "altname": "BCH",
      "decimals": 10,
      "display_decimals": 5
   }
}"#;

#[derive(Deserialize, Debug)]
struct Assets {  
    aclass: String,
    altname: String,
    decimals: u8,
    display_decimals: u8,
}

fn main() {
    let serde_value: HashMap<String, Assets> = serde_json::from_str(VALUE).unwrap();

    println!("{:?}", serde_value);
}

playground

Hoofbound answered 6/9, 2017 at 12:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.