gpt4 book ai didi

json - Elm:如何从JSON API解码数据

转载 作者:行者123 更新时间:2023-12-03 13:29:27 26 4
gpt4 key购买 nike

我有使用http://jsonapi.org/格式的数据:

{
"data": [
{
"type": "prospect",
"id": "1",
"attributes": {
"provider_user_id": "1",
"provider": "facebook",
"name": "Julia",
"invitation_id": 25
}
},
{
"type": "prospect",
"id": "2",
"attributes": {
"provider_user_id": "2",
"provider": "facebook",
"name": "Sam",
"invitation_id": 23
}
}
]
}


我的模型如下:

type alias Model = {
id: Int,
invitation: Int,
name: String,
provider: String,
provider_user_id: Int
}

type alias Collection = List Model


我想将json解码为Collection,但不知道如何。

fetchAll: Effects Actions.Action
fetchAll =
Http.get decoder (Http.url prospectsUrl [])
|> Task.toResult
|> Task.map Actions.FetchSuccess
|> Effects.task

decoder: Json.Decode.Decoder Collection
decoder =
?


如何实现解码器?谢谢

最佳答案

N.B. Json.Decode docs

试试这个:

import Json.Decode as Decode exposing (Decoder)
import String

-- <SNIP>

stringToInt : Decoder String -> Decoder Int
stringToInt d =
Decode.customDecoder d String.toInt

decoder : Decoder Model
decoder =
Decode.map5 Model
(Decode.field "id" Decode.string |> stringToInt )
(Decode.at ["attributes", "invitation_id"] Decode.int)
(Decode.at ["attributes", "name"] Decode.string)
(Decode.at ["attributes", "provider"] Decode.string)
(Decode.at ["attributes", "provider_user_id"] Decode.string |> stringToInt)

decoderColl : Decoder Collection
decoderColl =
Decode.map identity
(Decode.field "data" (Decode.list decoder))


棘手的部分是使用 stringToInt将字符串字段转换为整数。我按照API示例来说明什么是int和什么是字符串。我们有点运气的是, String.toInt返回了 Result所期望的 customDecoder,但是有足够的灵活性,您可以稍微复杂一些,并接受两者。通常,您会使用 map进行此类操作; customDecoder本质上是 map用于可能失败的功能。

另一个技巧是使用 Decode.at进入 attributes子对象。

关于json - Elm:如何从JSON API解码数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32575003/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com