Elm:如何从 JSON API 解码数据

2024-05-29

我有这个数据使用http://jsonapi.org/ http://jsonapi.org/ format:

{
    "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
            }
        }
    ]
}

我的模型如下:

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

 type alias Collection = List Model

我想将 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 =
  ?

如何实现解码器?谢谢


N.B. Json.Decode 文档 http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Decode

尝试这个:

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

棘手的部分是使用stringToInt将字符串字段转换为整数。我按照 API 示例了解什么是 int 和什么是 string。我们幸运一点String.toInt返回一个Result正如预期的那样customDecoder但有足够的灵活性,您可以变得更加成熟并接受两者。通常你会使用map对于这种事情;customDecoder本质上是map对于可能失败的功能。

另一个技巧是使用Decode.at进入attributes子对象。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Elm:如何从 JSON API 解码数据 的相关文章

  • json_encode 不使用 html 字符串作为值

    我现在正在调试这个ajax很长一段时间 我的 jQUery 文件中有这个 typeForm ajaxForm success function html alert html submit 这调用服务 php 其中我有这个 data arr
  • 具有 ISO 日期格式的 WCF REST JSON

    我在 WCF Web 服务 框架 4 0 中使用 JSON 支持 ISO 日期格式时遇到了一个大问题 我尝试了很多 但还没有运气 休息服务 WebInvoke Method PUT UriTemplate mvnoid OrderID Re
  • Json 将字符串中的 & 转换为 \u0026

    我正在尝试从 pdf 中提取文本并将其写入 json 文件 在提取 unicode 字符时 Json 将所有 转换为 u0026 例如我的实际字符串是 1588 代表 它正确打印到 txt 文件 控制台等 但是当我尝试将此字符串打印到 Js
  • JS Globalize - 加载 json cldr

    我的最新版本有问题globalize js 为了使用它 我必须加载cldr modules和语言定义 现在我从全球化文档中得到了这个例子 loading needed modules get Scripts cldr supplementa
  • 无法解析请求正文

    我一直在尝试解决以下错误 但无法解决 下面是代码 HttpPost public async Task
  • UIImage 在编码/解码时不等效

    我一直在对我的模型进行一些测试 以确保当我将它们编码为 JSON 然后使用它们解码回来时它们是相等的JSONEncoder Decoder 然而 我的一项测试失败了 罪魁祸首是UIImage 我已确保在编码 解码过程中没有抛出任何错误 首先
  • 仅允许 Firebase 实时数据库中的唯一值[重复]

    这个问题在这里已经有答案了 这是我的数据结构 root mydata KqI0uf 1 bD3oLlx2h Joe Kdk0bf 1 bx0oLlb9a Mike Kox8gf 1 b36onlT3h Eve 如何编写规则以仅允许 Fire
  • 警报 Json 对象

    我有以下 json 对象 我需要通过 javascript 提醒它 data empmenuid 1 empid null deptid 66 aliasid 66 firstname 66 lastname 66 sin 66 statu
  • UnicodeDecodeError:“utf8”编解码器无法解码位置 0 中的字节 0xa5:起始字节无效

    我在用Python 2 6 CGI脚本但在执行时在服务器日志中发现此错误json dumps Traceback most recent call last File etc mongodb server cgi bin getstats
  • 调试测试时从 local.setting.json 读取值

    在运行或调试测试时 我似乎无法从天蓝色函数中的该文件中读取任何内容 但是在本地调试整个应用程序时它工作得很好 任何人都可以解释为什么吗 IsEncrypted false Values xyz 123 var res Configurati
  • JSON数据通过JS/AJAX转化为PHP

    Goal 我正在使用 coinmarketcap com API link https api coinmarketcap com v1 ticker convert EUR 预先我将他们的数据转换成 PHP 样本 现在我想使用AJAX J
  • 将 JSON 数据传递到 Spring MVC 控制器

    我需要将 JSON 字符串发送到 Spring MVC 控制器 但我没有 有任何表单绑定 我只需要将纯 JSON 数据发送到 Controller 类 我正在对 Controller 方法进行 jQuery AJAX 调用 如下面的代码所示
  • 如何防止 gson 将整数转换为双精度数

    我的 json 中有整数 但我不希望 gson 将它们转换为双精度数 以下不起作用 Test public void keepsIntsAsIs String json id 1 quantity 2 name apple id 3 qua
  • 使用 json 模式强制对象非空

    我们可以强制类型对象的空属性如下 description voice mail record type object additionalProperties false properties 正如所解释的here https stacko
  • Elm - 将消息转换为 Cmd 消息

    我正在尝试修改一个简单的应用程序elm lang 教程 https guide elm lang org architecture effects http html首先更新模型 然后触发另一次更新 update msg model cas
  • Jackson - 将值传递给 JsonDeserializer

    我有一个现有的类层次结构 如下所示 public interface Service String getId String getName public class FooTask extends AbstractTask private
  • 将 jQuery 数组字符串转换为 PHP 数组

    首先 我得说我对 PHP 还很陌生 我正在尝试获取一个可以使用 foreach 的 PHP 对象 以下字符串通过 ajax 传递 我正在尝试转动以下字符串 menu title TEST1 href title TEST2 href QWE
  • 使用 slice 函数对 JSON 对象进行切片

    我想对 JSON 数组进行切片 但出现以下错误 对象 没有方法 切片 以下是我的代码 scope getPagedDataAsync function pageSize page searchText setTimeout function
  • Google Calendar JSON API:全天活动总是多一天

    Since recently the JSON API always seems to add a day when returning the timespan for full day events Display in Google
  • JSON.NET 使用 JObject、JToken 和 JArray 进行解析

    我有一个 json 字符串 我试图用 JSON net 解析它 我想循环并使用komponent大批 这是我的 json 字符串 Name Service jsonTEMPLATE komponent name aa name bb 这是我

随机推荐