Search code examples
rustserializationdeserializationserdetoml

Rust TOML reading table and key-value in order


How to read TOML in order?

I have this code:

  let toml_content: Value = contents.parse::<toml::Value>().unwrap();
  for key in toml_content.as_table().unwrap().keys() {
    println!("{:?}", key);
  }

Returning output:

"Community"
"Person"
"Wallet"

While I expect ordered output:

"Person"
"Wallet"
"Community"

Because I have this toml file, where Person is 1st:

[Person]
name = "str"
age = "u8"
ttl = "u8"
wallet = "Wallet"

[Wallet]
owner = "Person"
balance = "f64"

[Community]
name = "str"
members = ["Person"]

Solution

  • Assuming you're using the toml crate, enable the preserve_order feature. This is documented here.

    Add this into Cargo.toml

    [dependencies]
    toml = { version = "*", features = ["preserve_order"] }