Elm complex custom JSON decoder -
i have need decode json elm type below:
type
type user = anonymous | loggedin string type alias model = { email_id : user , id : id , status : int , message : string , accesstoken : accesstoken }
json message 1
{ "status": 0, "message": "error message explaining happened in server" }
into type value
model { "email_id": anonymous , id: 0 , status: 0 , message: json.message , accesstoken: "" }
json message 2
{ "status": 1, "email_id": "asdfa@asdfa.com" "token": "asdfaz.adfasggwegwegwe.g4514514ferf" "id": 234 }
into type value
model { "email_id": loggedin json.email_id , id: json.id , status: json.status , message: "" , accesstoken: json.token }
decoder information
above, "message" not present , email_id/id/token not present.
how type of conditional decoding in elm
json.decode.andthen
lets conditional parsing based on value of field. in case, looks you'll first want pull out value of "status" field, andthen
handle separately based on whether 1
or 0
.
edit 2016-12-15: updated elm-0.18
import html h import json.decode exposing (..) type user = anonymous | loggedin string type alias id = int type alias accesstoken = string type alias model = { email_id : user , id : id , status : int , message : string , accesstoken : accesstoken } modeldecoder : decoder model modeldecoder = (field "status" int) |> andthen modeldecoderbystatus modeldecoderbystatus : int -> decoder model modeldecoderbystatus status = case status of 0 -> map5 model (succeed anonymous) (succeed 0) (succeed status) (field "message" string) (succeed "") 1 -> map5 model (map loggedin (field "email_id" string)) (field "id" int) (succeed status) (succeed "") (field "token" string) _ -> fail <| "unknown status: " ++ (tostring status) main = h.div [] [ h.div [] [ decodestring modeldecoder msg1 |> result.tomaybe |> maybe.withdefault emptymodel |> tostring |> h.text ] , h.div [] [ decodestring modeldecoder msg2 |> result.tomaybe |> maybe.withdefault emptymodel |> tostring |> h.text ] ] emptymodel = model anonymous 0 0 "" "" msg1 = """ { "status": 0, "message": "error message explaining happened in server" } """ msg2 = """ { "status": 1, "email_id": "asdfa@asdfa.com" "token": "asdfaz.adfasggwegwegwe.g4514514ferf" "id": 234 } """
Comments
Post a Comment