Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to deserialize map with unknown keys? #1387

Closed
ZNackasha opened this issue Sep 12, 2018 · 2 comments
Closed

How to deserialize map with unknown keys? #1387

ZNackasha opened this issue Sep 12, 2018 · 2 comments
Labels

Comments

@ZNackasha
Copy link

ZNackasha commented Sep 12, 2018

I have a JSON file format in which there can be dynamic generated keys at the root position. the name of each key is unique and is not know at dissect time. The value of each key is standardized. I would like to deserialize the JSON so I can both deserialize the value and also keep the key.

here is a very basic example

{
 item1: {
  value: 5
 },
 item99: {
  value: 1
 },
}
@ZNackasha ZNackasha changed the title how to dissect on a unknow key name? How to dissect on a unknow key name? Sep 12, 2018
@ZNackasha ZNackasha changed the title How to dissect on a unknow key name? How to dissect on a unknow key? Sep 12, 2018
@dtolnay
Copy link
Member

dtolnay commented Sep 13, 2018

If the keys are strings and every value is the same type, I would recommend treating the data as a hash map. https://doc.rust-lang.org/std/collections/struct.HashMap.html

#[macro_use]
extern crate serde_derive;

extern crate serde;
extern crate serde_json;

use std::collections::HashMap;

#[derive(Deserialize, Debug)]
struct Item {
    value: u64,
}

fn main() -> serde_json::Result<()> {
    let j = r#"
        {
            "item1": { "value": 5 },
            "item99": { "value": 1 }
        }"#;

    let map: HashMap<String, Item> = serde_json::from_str(j)?;
    println!("hash map = {:#?}", map);

    Ok(())
}

@dtolnay dtolnay closed this as completed Sep 16, 2018
@dtolnay dtolnay changed the title How to dissect on a unknow key? How to deserialize map with unknown keys? Nov 9, 2018
@dtolnay dtolnay added the support label Nov 9, 2018
@dsherret
Copy link

This is the first result on google, so I just wanted to point out that if you do not know the types of the values, then you can just specify serde_json::Value as the hashmap value type:

let key_values: HashMap<String, serde_json::Value> = serde_json::from_str(&text)?;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

No branches or pull requests

3 participants