Decode Json Array with objects in Elm

二次信任 提交于 2019-12-04 16:35:58

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/39320948/decode-json-array-with-objects-in-elm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!