Elm Integrated JSON Decoder

I need to decrypt JSON as an elm tree as shown below:

A 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 what happened in server" } 

in 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 } 

in type value

 Model { "email_id": LoggedIn json.email_id , id: json.id , status: json.status , message: "" , accessToken: json.token } 

Decoder Information

Above, the “message” is not always present, and the email_id / id / token is always absent.

How to make this type of conditional decoding in elms

+5
source share
1 answer

Json.Decode.andThen allows Json.Decode.andThen to perform conditional parsing based on a field value. In this case, it looks like you first want to pull out the value of the "status" field, andThen process it separately, be it 1 or 0 .

Edit 2016-12-15: Updated to elm-0.18

 import Html as 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 what happened in server" } """ msg2 = """ { "status": 1, "email_id": " asdfa@asdfa.com " "token": "asdfaz.adfasggwegwegwe.g4514514ferf" "id": 234 } """ 
+8
source

Source: https://habr.com/ru/post/1242431/


All Articles