#Serde serialize all other fields into struct

2 messages · Page 1 of 1 (latest)

ivory halo
#

Hello, I'm moving from golang (cobra) to rust with clap to build CLI. I've stumbled onto issue that I've some trouble with. I have config file that contains some 'known' fields and any amount of 'unknown' fields. It'll be easier to explain with example config file.

services:
  serviceA:
    root: ./serviceA
    userDefinedField: somestr
    anotherUserDefinedField: anotherStr
  serviceB:
    root: ./serviceB
    thereCanBeUnlimitedAmountOfThoseFields: str

What i'd like is to have 'Service' struct such as:

struct Service {
  root: String
  // there may be more 'common' fields like root
  // all 'unknown' fields should be put into hashmap below
  fields: HashMap<String, String>
}

Is there any way to express that easily with serde or do I need to write custom Serializer?

ornate barn
#

I think you can just do flatten

#[derive(Serialize, Deserialize)]
struct Service {
  root: String
  #[serde(flatten)]
  fields: HashMap<String, String>
}