Skip to content

Instantly share code, notes, and snippets.

@freakingawesome
Created October 4, 2016 17:21
Show Gist options
  • Save freakingawesome/82109ca1b9eba8dbdef1fbd43293699c to your computer and use it in GitHub Desktop.
Save freakingawesome/82109ca1b9eba8dbdef1fbd43293699c to your computer and use it in GitHub Desktop.
import Html exposing (text)
import Json.Decode as Json exposing (Decoder, (:=))
import Dict exposing (Dict)
type Player = Player Int PlayerContents
type alias PlayerContents =
{ name : String
, team : Team
}
type Team = Team Int TeamContents
type alias TeamContents =
{ name : String
, players : List Player
}
main =
text <| toString <| Json.decodeString (payloadDecoder) json
teamDecoder : Decoder Team
teamDecoder =
Json.object2 TeamContents
("name" := Json.string)
(Json.succeed [])
`Json.andThen` \contents ->
"id" := Json.int `Json.andThen` \teamID ->
Json.succeed <| Team teamID contents
payloadDecoder : Decoder (List Player, List Team)
payloadDecoder =
"teams" := Json.list teamDecoder
`Json.andThen` \teams ->
let
teamLookup =
List.map (\(Team id _ as t) -> (id, t)) teams
|> Dict.fromList
appendPlayers players (Team teamID contents as t) =
let filtered = List.filter (\p -> getTeamID p == teamID) players
in Team teamID { contents | players = filtered }
in
"players" := Json.list (playerDecoder teamLookup)
`Json.andThen` \players ->
let populatedTeams =
List.map (appendPlayers players) teams
in
Json.succeed (players, populatedTeams)
getTeamID : Player -> Int
getTeamID (Player _ contents) =
case contents.team of
Team tID _ -> tID
playerDecoder : Dict Int Team -> Decoder Player
playerDecoder teamLookup =
let
team id =
case Dict.get id teamLookup of
Nothing -> Json.fail <| "Could not find team ID " ++ (toString id)
Just t -> Json.succeed t
in
"teamId" := Json.int `Json.andThen` \teamID ->
"id" := Json.int `Json.andThen` \playerID ->
Json.object2 PlayerContents
("name" := Json.string)
(team teamID)
`Json.andThen` \contents ->
Json.succeed <| Player playerID contents
json =
"""
{
"players": [
{ "id": 100, "name": "Sam Bradford", "teamId": 200 },
{ "id": 101, "name": "Kyle Rudolph", "teamId": 200 },
{ "id": 102, "name": "Matthew Stafford", "teamId": 201 },
{ "id": 103, "name": "Marvin Jones Jr.", "teamId": 201 },
{ "id": 104, "name": "Golden Tate", "teamId": 201 }
],
"teams": [
{ "id": 200, "name": "Minnesota Vikings" },
{ "id": 201, "name": "Detroit Lions" }
]
}"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment