Elm dynamically loading a decoder based on previous field

56 views
Skip to first unread message

Nima Birgani

unread,
Dec 2, 2016, 8:11:45 PM12/2/16
to Elm Discuss
Hi all,

I'm trying to decode an relatively large JSON to run my app in elm. here is the how my json looks like:

{
  "pageTitle" : "users",
  "primaryWidget" : "user"
  "primaryWidgetData" : {
    "permissions" : ["read", "write"]
    "data": [
      {
        "name": "name 1"
        "email" : "some...@sd.cs"
        "id": "dsd33-wdsds"
      },
      {
        "name": "name 2"
        "email" : "ano...@sd.cs"
        "id": "0000-wdsds"
      }
    ]
  } 
}

alternatively my json can be like:

{
  "pageTitle" : "accounts",
  "primaryWidget" : "account-manager"
  "primaryWidgetData" : {
    "accounts": [
      {
        "accountId": "id 1"
        "accountName" : "acc name"
        "owner": {
          "name": "name 2"
          "email" : "ano...@sd.cs"
          "id": "0000-wdsds"
        }
      },
      {
        "accountId": "id 2"
        "accountName" : "acc name 2"
        "owner": {
          "name": "name 1"
          "email" : "so...@sd.cs"
          "id": "3343-wdsds"
        }
      }
    ]
  }
}

when I'm decoding the JSON i would like to load  the relevant decoder based on the "primaryWidget" and I'm using pipeline decoder:

manifestDecoder : Decoder Manifest
manifestDecoder =
    Json.decode Manifest
        |> required "pageTitle" string
        |> required "primaryWidget" (string |> andThen primaryWidgetDecoder)
        |> required "primaryWidgetDat"  now I want to pass the relevant loader here but I have no Idea how. tried to use andThen but no luck 


Many thanks for reading and helping.

Cheers,


Max Goldstein

unread,
Dec 2, 2016, 9:10:25 PM12/2/16
to Elm Discuss
Json.Decode.andThen. It takes the result of the previous deciding operation and uses it to produce a new decoder.

If you need more to go on, let us know.

Leroy Campbell

unread,
Dec 2, 2016, 10:45:22 PM12/2/16
to Elm Discuss
I've posted a full example here:


If it'd be helpful, I can work on a writeup to explain my design choices.

Nima Birgani

unread,
Dec 2, 2016, 11:33:47 PM12/2/16
to Elm Discuss
Thank you both for your help. Leroy, your gist is exactly what I wanted. Thanks again.
--
You received this message because you are subscribed to a topic in the Google Groups "Elm Discuss" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/elm-discuss/9uL8cqKNL9g/unsubscribe.
To unsubscribe from this group and all its topics, send an email to elm-discuss...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Nima Birgani

unread,
Dec 3, 2016, 12:52:34 PM12/3/16
to elm-d...@googlegroups.com
Leroy,

Last night I did not realize that you created this gist just to help me. I thought you had it for your own project!. I owe you big time man. Thanks a lot!

Cheers,

Nima

Reply all
Reply to author
Forward
0 new messages