Elm: Cómo decodificar datos de la API JSON
(1)
Prueba esto:
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))
La parte difícil es usar stringToInt para convertir los campos de cadena en números enteros. He seguido el ejemplo de API en términos de qué es un int y qué es una cadena. Tuvimos la suerte de que String.toInt devuelva un Result como lo espera customDecoder pero hay suficiente flexibilidad para que pueda ser un poco más sofisticado y aceptar ambos. Normalmente usarías el map para este tipo de cosas; customDecoder es esencialmente un map de funciones que pueden fallar.
El otro truco era usar Decode.at para ingresar al objeto secundario de attributes .
Tengo estos datos utilizando el formato 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
}
}
]
}
Tengo mis modelos como:
type alias Model = {
id: Int,
invitation: Int,
name: String,
provider: String,
provider_user_id: Int
}
type alias Collection = List Model
Quiero decodificar el json en una colección, pero no sé cómo.
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 =
?
¿Cómo implemento decodificador? Gracias