Elm: How to decode data from JSON API

后端 未结 1 1193
没有蜡笔的小新
没有蜡笔的小新 2021-02-05 09:11

I have this data using http://jsonapi.org/ format:

{
    \"data\": [
        {
            \"type\": \"prospect\",
            \"id\": \"1\",
            \"attri         


        
1条回答
  •  既然无缘
    2021-02-05 09:38

    N.B. Json.Decode docs

    Try this:

    import Json.Decode as Decode exposing (Decoder)
    import String
    
    -- 
    
    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.

    0 讨论(0)
提交回复
热议问题