Elm:如何从JSON API解码数据
我使用以下格式获取此数据: 我的模型如下:Elm:如何从JSON API解码数据,json,elm,Json,Elm,我使用以下格式获取此数据: 我的模型如下: type alias Model = { id: Int, invitation: Int, name: String, provider: String, provider_user_id: Int } type alias Collection = List Model 我想将json解码成一个集合,但不知道如何解码 fetchAll: Effects Actions.Action fetchAll = Http.g
type alias Model = {
id: Int,
invitation: Int,
name: String,
provider: String,
provider_user_id: Int
}
type alias Collection = List Model
我想将json解码成一个集合,但不知道如何解码
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 =
?
如何实现解码器?谢谢
试试这个:
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))
import Json.Decode as Decode exposing(解码器)
导入字符串
--
stringToInt:解码器字符串->解码器整型
弦状突=
Decode.customDecoder d String.toInt
解码器:解码器模型
译码器=
Decode.map5模型
(Decode.field“id”Decode.string |>stringToInt)
(Decode.at[“attributes”,“investment_id”]Decode.int)
(Decode.at[“attributes”,“name”]Decode.string)
(Decode.at[“属性”,“提供程序”]Decode.string)
(Decode.at[“attributes”,“provider_user_id”]Decode.string |>stringToInt)
解码器集合:解码器集合
解码卷=
解码.map标识
(解码字段“数据”(解码列表解码器))
棘手的部分是使用stringToInt
将字符串字段转换为整数。我在什么是int和什么是字符串方面遵循了API示例。我们幸运地发现,String.toInt
返回了结果
,正如customDecoder
所期望的那样,但是有足够的灵活性,您可以变得更复杂一些,并接受这两种结果。通常你会用map
来做这类事情customDecoder
本质上是针对可能失败的功能的map
另一个技巧是使用
解码。at
进入属性
子对象。如果您还解释了如何将值映射到结果,我可能会很有用。OP只询问了如何实现解码器。要获得结果,请调用Json.Decode.decodeString
或decodeValue
。:=
现在是Decode.field
。我已经更新了示例。最后一步应该是decoderColl=Decode.map identity(Decode.field“data”(Decode.list decoder))
。
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))