Sam Phillips
Sam Phillips

Reputation: 265

Json.Decode.Pipeline trouble with optional

I'm having some trouble decoding optional fields from a JSON string. I am trying to decode "plannings" and a planning can be of two types, a normal planning, or a flex planning. If it is a normal planning, it will have the a planning_id, if it is a flex planning, it will have a flexplanning_id. In the record in which I will store plannings, both planningId and fiexplanningId are of type Maybe Int.

type alias Planning =
    { time : String
    , planningId : Maybe Int
    , groupId : Int
    , groupName : String
    , flex : Bool
    , flexplanningId : Maybe Int
    , employeeTimeslotId : Maybe Int
    , employeeId : Int
    }

And here is the decoder I use:

planningDecoder : Decoder Planning
planningDecoder =
    decode Planning
        |> required "time" string
        |> optional "planning_id" (nullable int) Nothing
        |> required "group_id" int
        |> required "group_name" string
        |> required "flex" bool
        |> optional "employee_timeslot_id" (nullable int) Nothing
        |> optional "flexplanning_id" (nullable int) Nothing
        |> required "employee_id" int

However, the decoder isn't accurately decoding and storing the data from JSON. Here is an example. This is one piece of the string returned by a request made by my application:

"monday": [
{
"time": "07:00 - 17:00",
"planning_id": 6705,
"group_name": "De rode stip",
"group_id": 120,
"flex": false,
"employee_timeslot_id": 1302,
"employee_id": 120120
},
{
"time": "07:00 - 17:00",
"group_name": "vakantie groep",
"group_id": 5347,
"flexplanning_id": 195948,
"flex": true,
"employee_id": 120120
}
],

This, however, is the result of the decoder:

{ monday = [
  { time = "07:00 - 17:00"
  , planningId = Just 6705
  , groupId = 120
  , groupName = "De rode stip"
  , flex = False, flexplanningId = Just 1302
  , employeeTimeslotId = Nothing
  , employeeId = 120120 }
 ,{ time = "07:00 - 17:00"
  , planningId = Nothing
  , groupId = 5347
  , groupName = "vakantie groep"
  , flex = True
  , flexplanningId = Nothing
  , employeeTimeslotId = Just 195948
  , employeeId = 120120 
  }
 ],

As you can see, in the JSON, there are two plannings, one with a planning_id and the other with a flexplanning_id. However, in the record produced by the decoder, the first planning has both a planningId and a flexplanningId, whereas the second has neither.

Upvotes: 1

Views: 685

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36385

You need to flip these two lines in the decoder to match the order in which they are defined:

|> optional "employee_timeslot_id" (nullable int) Nothing
|> optional "flexplanning_id" (nullable int) Nothing

They are defined in this order:

, flexplanningId : Maybe Int
, employeeTimeslotId : Maybe Int

Upvotes: 4

Related Questions