Created
June 22, 2020 13:10
-
-
Save vyuh/d8a360f4cd77a51617e37b9450887010 to your computer and use it in GitHub Desktop.
ELM: Encoding Custom Types to JSON. Decoding Custom Types from JSON.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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