JSON Decode question

109 views
Skip to first unread message

Eelco Hoekema

unread,
May 18, 2016, 5:28:59 PM5/18/16
to Elm Discuss
Hi,

I'm a bit stuck in decoding some json. In http://package.elm-lang.org/packages/elm-lang/core/4.0.0/Json-Decode#andThen there is an example of decoding a tagged union for a shape. 
type Shape
    = Rectangle Float Float
    | Circle Float

shape : Decoder Shape
shape =
  ("tag" := string) `andThen` shapeInfo

shapeInfo : String -> Decoder Shape
shapeInfo tag =
  case tag of
    "rectangle" ->
        object2 Rectangle
          ("width" := float)
          ("height" := float)

    "circle" ->
        object1 Circle
          ("radius" := float)

    _ ->
        fail (tag ++ " is not a recognized tag for shapes")

How would the corresponding JSON look like? Should that be 

{"rectangle" : {"width" : "2", "height": "3"}}



eelco

Mario Sangiorgio

unread,
May 18, 2016, 5:37:01 PM5/18/16
to elm-d...@googlegroups.com
No, the json explicitly has a tag attribute to let your code know what is the shape type it encodes followed by the attributes for that shape.

Something like:
{ "tag": "rectangle", "width": "2", "height": "3"}
{ "tag": "circle", "radius": "2"}

Note that there is no nesting.

Mario

--
You received this message because you are subscribed to the Google Groups "Elm Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elm-discuss...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Mario Sangiorgio

unread,
May 18, 2016, 5:51:50 PM5/18/16
to elm-d...@googlegroups.com
Actually you need width, height and radius to be numbers not strings. Otherwise you'll get parsing errors.
{ "tag": "rectangle", "width": 2, "height": 3}
{ "tag": "circle", "radius": 2}

Eelco Hoekema

unread,
May 19, 2016, 4:03:30 AM5/19/16
to elm-d...@googlegroups.com
Thanks! I was making things too complex, apparently. 

Am i correct that the assumption here is that "tag" MUST be the first string the decoder runs into? So if my backend returns the JSON with alphabetically sorted keys { "height": 3, "tag": "rectangle", "width": 2}, the decoder will run into an error?

eelco

Janis Voigtländer

unread,
May 19, 2016, 4:58:12 AM5/19/16
to elm-d...@googlegroups.com
No, the order in the input is irrelevant.
Reply all
Reply to author
Forward
0 new messages