18

I recently tried to get data from server with Elm's Http module and i'm stuck with decoding json to custom types in Elm.

My JSON looks like that:

[{
    "id": 1,
    "name": "John",
    "address": {
        "city": "London",
        "street": "A Street",
        "id": 1
    }
},
{
    "id": 2,
    "name": "Bob",
    "address": {
        "city": "New York",
        "street": "Another Street",
        "id": 1
    }
}]

Which should be decoded to:

type alias Person =
{
 id : Int,
 name: String,
 address: Address
}

type alias Address = 
{
 id: Int,
 city: String,
 street: String
 }

What i found so far is that i need to write a decoder function:

personDecoder: Decoder Person
personDecoder =
  object2 Person
    ("id" := int)
    ("name" := string)

That for the first two properties but how i integrate the nested Address property and how combine this to decode the list?

rubiktubik
  • 961
  • 2
  • 12
  • 28

1 Answers1

29

You first need an Address Decoder similar to your Person Decoder

Edit: Upgraded to Elm 0.18

import Json.Decode as JD exposing (field, Decoder, int, string)

addressDecoder : Decoder Address
addressDecoder =
  JD.map3 Address
    (field "id" int)
    (field "city" string)
    (field "street" string)

Then you can use that for the "address" field:

personDecoder: Decoder Person
personDecoder =
  JD.map3 Person
    (field "id" int)
    (field "name" string)
    (field "address" addressDecoder)

A list of persons can be decoded like this:

personListDecoder : Decoder (List Person)
personListDecoder =
  JD.list personDecoder
Emanegux
  • 1,092
  • 2
  • 20
  • 38
Chad Gilbert
  • 36,115
  • 4
  • 89
  • 97
  • how would you use this with `Task.perform` and `Http.get`? I get a type error when using Http.get, it says it won't work with a `Decoder (List a)` and will only work with `Decoder a`. –  Sep 21 '16 at 17:53
  • 1
    @omouse - without seeing your code I can only guess (it sounds like you may have mismatched type parameters in the `Msg` you're sending for the success function) - but you may be better served by opening a new question or asking in the Slack channel if that isn't it – Chad Gilbert Sep 21 '16 at 18:04
  • @ChadGilbert posted it as a question: http://stackoverflow.com/questions/39628213/task-perform-is-expecting-the-3rd-argument-to-be-a-different-type didn't realize there's a Slack channel, I've been using IRC. –  Sep 22 '16 at 00:09