2

I'm trying to deserialise a JSON structure using serde, but where some of the field names can be different across different environments. For example:

In dev:

{
    "fields": {
        "field004": "This is the title",
        "field012": 456123
    }
}

In prod:

{
    "fields": {
        "field023": "This is the title",
        "field005": 456123
    }
}

Since the names do not change over time, I have them stored in an external config that can be easily retrieved into the app at runtime, but I want to avoid having to hard-code them into the structs I've build to handle the deserialisation (such as in this question) and I cannot figure out a way to get the field names retrieved from my config to be used in the deserialisation.

All other results I've found when searching for a solution to this do not address the specific problem I have.

Is there a way to specify the name of a field at runtime, or am I going to have to manually implement a deserialiser for it and use the config-fed field names that way?

Sid Holland
  • 2,871
  • 3
  • 27
  • 43
  • 2
    It might be possible if you use [untyped JSON values](https://github.com/serde-rs/json#operating-on-untyped-json-values). Otherwise, I don't think you can do it without listing the options in the attribute. – Herohtar Aug 16 '20 at 04:02
  • @Herohtar Thanks for the suggestion. I'd considered that, but the structure of the JSON I'm working with is actually quite deep so I'd end up with a lot of work to do once I'd got the `Value` back. I'd almost end up implementing a deserialiser but in a different fashion. – Sid Holland Aug 16 '20 at 04:07
  • Could the same field name from dev be used in prod for a dfifferent purpose? – Peter Hall Aug 16 '20 at 04:23
  • @PeterHall Unfortunately, yes. – Sid Holland Aug 16 '20 at 04:24
  • @SidHolland you can create a dedicated struct for `fields` with [a custom deserialization scheme](https://serde.rs/impl-deserializer.html), this way you can transform the fields however you want, possibly based on an envvar. Alternatively, if the "dev" versus "prod" thing is known at compile-time you could just use a conditional struct (one version would be customised for the production environment and the other for the development one). – Masklinn Aug 16 '20 at 10:27

0 Answers0