将JSON解码为Elm也许吧

Mat*_*kin 10 json decode elm

给出以下JSON:

[
  {
    "id": 0,
    "name": "Item 1",
    "desc": "The first item"
  },
  {
    "id": 1,
    "name": "Item 2"
  }
]
Run Code Online (Sandbox Code Playgroud)

如何将其解码为以下模型:

type alias Model =
    { id : Int
    , name : String
    , desc : Maybe String
    }
Run Code Online (Sandbox Code Playgroud)

bdu*_*kes 18

Brian Hicks在JSON解码器上有一系列帖子,您可能希望专门查看Adding New Fields to Your JSON Decoder(处理可能会或可能不会从JSON对象接收字段的场景).

首先,您可能想要使用elm-decode-pipeline包.然后,您可以使用该optional函数声明您的desc字段可能不在那里.布赖恩在文章中指出的那样,你可以使用maybe解码器的核心Json.Decode组件,但它会产生Nothing任何故障,而不仅是提供null.这里一个nullable解码器,你也可以考虑使用,如果你不想使用管道模块.

你的解码器看起来像这样:

modelDecoder : Decoder Model
modelDecoder =
    decode Model
        |> required "id" int
        |> required "name" string
        |> optional "desc" (Json.map Just string) Nothing
Run Code Online (Sandbox Code Playgroud)

这是Ellie的一个实例.


toa*_*tal 10

因此,如果您正在寻找不需要的零依赖解决方案Json.Decode.Pipeline.

import Json.Decode as Decode exposing (Decoder)


modelDecoder : Decoder Model
modelDecoder =
    Decode.map3 Model
        (Decode.field "id" Decode.int)
        (Decode.field "name" Decode.string)
        (Decode.maybe (Decode.field "desc" Decode.string))
Run Code Online (Sandbox Code Playgroud)

如果你想使用Model构造函数作为applicative functor(因为你需要更多8个项目).

import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Extra as Decode


modelDecoder : Decoder Model
modelDecoder =
    Decode.succeed Model
        |> Decode.andMap (Decode.field "id" Decode.int)
        |> Decode.andMap (Decode.field "name" Decode.string)
        |> Decode.andMap (Decode.maybe (Decode.field "desc" Decode.string))
Run Code Online (Sandbox Code Playgroud)

两者都可以与Lists一起使用Decode.list modelDecoder.我希望应用函数在标准库中,但是您必须进入所有*-extra库才能获得这些功能.了解应用程序仿函数如何工作将有助于您了解更多内容,因此我建议阅读它们.Decode Pipeline解决方案抽象了这个简单的概念,但是当您遇到s Result.andMap或其他任何需求时,andMap因为没有mapN适合您的模块或DSL,您将知道如何获得解决方案.