rubiktubik rubiktubik - 3 months ago 25
JSON Question

Decode Json Array with objects in Elm

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?

Answer

You first need an Address Decoder similar to your Person Decoder

addressDecoder : Decoder Address
addressDecoder =
  object3 Address
    ("id" := int)
    ("city" := string)
    ("street" := string)

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

personDecoder: Decoder Person
personDecoder =
  object3 Person
    ("id" := int)
    ("name" := string)
    ("address" := addressDecoder)

A list of persons can be decoded like this:

personListDecoder : Decoder (List Person)
personListDecoder =
  list personDecoder