Skip to content

Convert from {"type": "foo", ...} json data to variant values #47

@jchavarri

Description

@jchavarri

Is there a simple way to convert from values like

{"type": "Image", "url": "https://example.com/ocean123.jpg"}
{"type": "Text", "title": "Cheeses Around the World", "body": "..."}

to variant values like

["Image", {"url": "https://example.com/ocean123.jpg"}]
["Text", {"title": "Cheeses Around the World", "body": "..."}]

In atdgen, there is a directive called ocaml.adapter that is similar to decco.codec but runs a bit earlier, and instead converts from Json.t to Json.t, just to do some preliminary massaging to the json values so they can be parsed properly.

Maybe something like this could exist in decco:

[@decco {adapter: (normalize, restore)}]
type t =
  | Image(image)
  | Text(string);

With a provided module to convert from json values where type key drives the variant used:

[@decco {adapter: TypeField.adapt}]
type t =
  | Image(image)
  | Text(string);

The TypeField module is also inspired in atdgen, which provides a similar thing out of the box: https://github.com/ahrefs/bs-atdgen-codec-runtime/blob/a40203875041e49bb78d2a46cb77f4b637865bae/src/atdgen_codec_runtime.ml#L15-L57

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions