Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use default values in a JSON decoder?

Tags:

elm

I make a JSON request to a web API about books. My responses usually look like

{
    "status": "successful",
    "author": "Roald Dahl",
    "title": "Charlie and the Chocolate Factory"
}

So I decode it to a Book type using the author and title fields.

But sometimes, the requested book won't be in the database, so my response is just

{
    "status": "failed"
}

In this case I'd still look to return a Book type, but with the author and title set to "NOT FOUND".

I'm reading the JSON documentation, but I'm not sure if anything there is helpful to me or if I can even do this in Elm in a simple way. Would appreciate some advice.

like image 389
GreenTriangle Avatar asked Dec 11 '25 05:12

GreenTriangle


2 Answers

You can either use Json.Decode.oneOf and add Json.Decode.succeed "NOT FOUND"as the last option OR, better use Json.Decode.andThen, first decode the status and then produce a Maybe Book (Just Book if status is successful and Nothing if it failed)

If there are more than one way it can fail, you could use Result instead of Maybe.

like image 151
pdamoc Avatar answered Dec 14 '25 09:12

pdamoc


You could also use the optional function at Evan's Json.Decode.Pipeline.

Then you can write it like this:

type alias User =
  { id : Int
  , name : String
  , email : String
  }


userDecoder : Decoder User
userDecoder =
  decode User
    |> required "id" int
    |> optional "name" string "blah"
    |> required "email" string

If you need to distinguish missing values and null values, this example is offered in the docs:

userDecoder2 =
    decode User
        |> required "id" int
        |> optional "name" (oneOf [ string, null "NULL" ]) "MISSING"
        |> required "email" string
like image 40
Marcelo Lazaroni Avatar answered Dec 14 '25 10:12

Marcelo Lazaroni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!