The inconsistency API design in JSON decoder ...?

I’m new to Elm and learning it! It’s very cool!

I have a question and I want to have some feedback, thanks!

Take the example from here: How to decode complex JSON with Elm? // Tech @ ChefClub //

type alias Record =
    { uid : String
    , age : Maybe Int
    , version : Float
    }


customDecoder : JD.Decoder Record
customDecoder =
    decode Record
        |> required "uid" JD.string
        |> optional "age" (JD.maybe JD.int) Nothing
        |> hardcoded 1.0

I’m wondering why field names sometimes appear in the decoder, and sometimes don’t?

If the field name is good for readability, why the usage here is not

customDecoder =
    decode Record
        |> required "uid" JD.string
        |> optional "age" (JD.maybe JD.int) Nothing
        |> hardcoded "version" 1.0

If the parameter order is enough, then why the usage here is not

customDecoder =
    decode Record
        |> required JD.string
        |> optional (JD.maybe JD.int) Nothing
        |> hardcoded 1.0

I’m wondering if there’s an inconsistency API design issue in JSON decoder here …?

Thanks for any feedback!

The field names match up with the names of the JSON object properties.

The positions match up with the order of the fields in the Record record.

If you want to read something out of the JSON, you do need the name. What hardcoded does is ignore the JSON object and just put the provided value in the next field of the record.

2 Likes

To make the above more obvious: You could write your whole Decoder like this:

customDecoder : JD.Decoder Record
customDecoder =
    decode (\uuid age -> { uuid = uuid, age = age, version = 1.0 })
        |> required "uid" JD.string
        |> optional "age" (JD.maybe JD.int) Nothing

I generally recommend this approach

2 Likes

Got it! Thank you very much!

Thanks for the example & link!
It helps me a lot!
Will learn more with them! Thanks!

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.