janestreet / ppx_yojson_conv

[@@deriving] plugin to generate Yojson conversion functions
MIT License
58 stars 8 forks source link

Would it be possible to serialize variants "anonymously"? #6

Open anentropic opened 3 years ago

anentropic commented 3 years ago

I am trying to serialize a JSON list which contains objects of two different kinds, like:

{
  "runs-on": "ubuntu",
  "steps": [
    {
      "use": "some value",
      "name": "whatever"
    },
    {
      "run": "some value",
      "name": "whatever"
    }
  ]
}

I thought I could model this with record and variant types like:

type step = [
  | `Run of RunStep.t
  | `Use of UseStep.t
]
[@@deriving yojson]

type job = {
  runs_on: string; [@key "runs-on"]
  steps: step list;
}
[@@deriving yojson]

But when I serialize this I get:

{
  "runs-on": "ubuntu",
  "steps": [
    ["Use", {
      "use": "some value",
      "name": "whatever"
    }],
    ["Run", {
      "run": "some value",
      "name": "whatever"
    }]
  ]
}

To me it doesn't seem useful to serialize the names of the variant constructors like this. I think if I ever did want that shape of output maybe I could explicitly specify a tuple or something in the type that I'm deriving from.

Is there any way I can suppress this behaviour and serialize the variant "anonymously"? (while still deriving from a record type)