serde_with icon indicating copy to clipboard operation
serde_with copied to clipboard

Convert a map to a list of single elements

Open jonasbb opened this issue 3 years ago • 1 comments

Sometimes it makes sense to deserialize a map as a list of single items, i.e., Vec<T>. The map-key becomes a special field in T.

{
	"id0": {
		"field_a": ...,
		...
	},
	"id1": {...},
	"id2": {...}, 
}

This could be converted to:

struct Data {
	id: IdType,
	field_a: ...,
	field_b: ...,
}

Prior art: https://crates.io/crates/serde-key-value-vec-map

jonasbb avatar Aug 07 '21 19:08 jonasbb

EDIT: This is available as serde_with::EnumMap

A slightly different transformation is between a map and a Vec of enums like #375. The key is the tag of the enum.

Serialize a Vec of externally tagged enums to a map with the map key being the external tag.

vec![
    EnumValue::Int(123),
    EnumValue::String("FooBar".to_string()),
    EnumValue::Int(456),
    EnumValue::String("XXX".to_string()),
    EnumValue::Unit,
    EnumValue::Tuple(1, "Middle".to_string(), false),
    EnumValue::Struct {
        a: 666,
        b: "BBB".to_string(),
        c: true,
    },
],

gets converted into this JSON

{
  "Int": 123,
  "String": "FooBar",
  "Int": 456,
  "String": "XXX",
  "Unit": null,
  "Tuple": [
    1,
    "Middle",
    false
  ],
  "Struct": {
    "a": 666,
    "b": "BBB",
    "c": true
  }
}

This got requested here: https://github.com/serde-rs/json/issues/743

jonasbb avatar Nov 06 '21 23:11 jonasbb

There is an implementation for the first post in #555. You both indicated interest in the feature. If you still need the feature and could leave some feedback at #555, that would be very much appreciated. @ncfavier @latk

jonasbb avatar Mar 02 '23 22:03 jonasbb