简体   繁体   English

榆树:如何解码来自JSON API的数据

[英]Elm: How to decode data from JSON API

I have this data using http://jsonapi.org/ format: 我使用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
            }
        }
    ]
}

I have my models like: 我有我的模特:

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

 type alias Collection = List Model

I want to decode the json into a Collection, but don't know how. 我想将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 =
  ?

How do I implement decoder? 我如何实现解码器? Thanks 谢谢

NB Json.Decode docs NB 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. 棘手的部分是使用stringToInt将字符串字段转换为整数。 I've followed the API example in terms of what is an int and what is a string. 我根据什么是int以及什么是字符串来遵循API示例。 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. 我们幸运的是, String.toInt按照customDecoder预期返回了一个Result ,但是有足够的灵活性可以让你更复杂并接受它们。 Normally you'd use map for this sort of thing; 通常你会使用map来做这种事情; customDecoder is essentially map for functions that can fail. customDecoder实际上是可以失败的函数的map

The other trick was to use Decode.at to get inside the attributes child object. 另一个技巧是使用Decode.at来获取attributes子对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM