Decoding Json Array with objects in Elm

I recently tried to get data from a server with an Elm Http module, and I was stuck with json decryption for user types in Elm.

My JSON looks like this:

[{ "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:

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

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

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

This is for the first two properties, but how do I integrate the Address attached property and how do I combine it to decode the list?

+7
json elm
source share
1 answer

First you need an address decoder similar to your personal decoder

Edit: updated 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 this for the address field:

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

The list of persons can be decoded as follows:

 personListDecoder : Decoder (List Person) personListDecoder = JD.list personDecoder 
+15
source share

All Articles