Skip to content

Instantly share code, notes, and snippets.

@vyuh
Created June 22, 2020 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vyuh/d8a360f4cd77a51617e37b9450887010 to your computer and use it in GitHub Desktop.
Save vyuh/d8a360f4cd77a51617e37b9450887010 to your computer and use it in GitHub Desktop.
ELM: Encoding Custom Types to JSON. Decoding Custom Types from JSON.
type Custom = Custom String
type alias P = { i : Int, s: String, c: Custom }
p = P 4 "mo" (Custom "jo")
import Json.Encode as E
import Json.Decode as D
enc : P -> E.Value
enc a = E.object [("c", E.string (case a.c of Custom str -> str)), ("i", E.int a.i), ("s", E.string a.s)]
j = enc p
json = E.encode 0 j
dec : D.Decoder P
dec = D.map3 P (D.field "i" D.int) (D.field "s" D.string) (D.field "c" D.string |> D.andThen (\str -> D.succeed (Custom str)))
D.decodeString dec json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment