Elm: How to decode data from JSON API

僤鯓⒐⒋嵵緔 提交于 2019-12-03 02:49:49

N.B. Json.Decode docs

Try this:

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))

The tricky part is using stringToInt to turn string fields into integers. I've followed the API example in terms of what is an int and what is a string. We luck out a little that String.toInt returns a Result as expected by customDecoder but there's enough flexibility that you can get a little more sophisticated and accept both. Normally you'd use map for this sort of thing; customDecoder is essentially map for functions that can fail.

The other trick was to use Decode.at to get inside the attributes child object.

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