How do you represent Maybe and Custom Types as json?

This is a follow-up question from “Staying sane with Maybe”.

The only discussion I’ve found on here that touches on storing types as json suggests using elm-codec, but I’m not sure how to integrate that with Json.Decode or Json.Decode.Pipeline (there’s not many examples given) and it seems like overkill for simple types?

What’s the simplest way to make this happen, without plugins?

I think I remember seeing Evan talk about saving custom types as SQL in the database (in the future), but what’s the best way to model these in json? I understand there’s no way to store types as json, and there’s limited json data types, but what about …

  1. A Maybe type.
    • Would Nothing be represented simply as [], 0, null, or false?
    • Is Maybe generally used for application state only?
  2. Take a simple example like Colour below
    • What’s the best way to encode and decode these?
  3. Perhaps you can give other examples you’ve discovered

I’ll caveat this by saying I’ve mostly decodeed and haven’t done any encodeing as of yet.

type Colour
    = Light
    | Dark

helper colour =
    case colour of
        Light -> "light"
        Dark -> "dark"

Perhaps this is a CSS class that’s converted to "light" or "dark" strings with a case statement when a user clicks a button. How would you encode/decode that as json? Just store it in your record as a string and use that object to encode with? A simple helper function?

type Colour
    = Cyan percentage
    | Magenta percentage
    | Yellow percentage
    | Black percentage

Perhaps you have a colour picker that’s user generated. Would you just save this as a List percentage? Is there a better way to represent the custom type?

These might be overly simplistic or bad examples, I don’t know … but as far as I’m aware custom types allow you to be more specific within your app and add some type safety too. Does it matter how you store these?

How are you guys handling this when it comes to storing as json? How do you convert these from json->type and type->json? What problems have you found?

Nothing, translates well to null.

e.g. Json.Decode - json 1.1.3

For other custom types, reaching for a codec library is a good idea. As you will need to have metadata in your json to identify the variants in your custom types. The codec libraries take care of that e.g. they add a property like __tag__ or something similar.

However, maybe rethink storing those directly, as your custom types in your app can get out of sync with your stored data very quickly. You would have to version your custom types and deal with that. I think these codec libs are fine for transmitting the data. But you probably don’t want to store it as is.

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.