如何在榆树中将元组编码为 JSON

How to encode tuple to JSON in elm

我有 (String,Bool) 的元组需要编码为 JSON 榆树中的数组。

下面的link对原始类型和其他列表、数组和对象很有用。但是我需要对 tuple2 进行编码。

参考:http://package.elm-lang.org/packages/elm-lang/core/4.0.3/Json-Encode#Value

我尝试了不同的方法,例如使用 toString 函数对元组进行编码。 它没有给我 JSON 数组,而是生成如下所示的字符串 "(\"r"\,False)".

JSON.Decoder 期望输入参数解码如下片段。

decodeString (tuple2 (,) float float) "[3,4]"

参考:http://package.elm-lang.org/packages/elm-lang/core/4.0.3/Json-Decode

问:tuple2有decode函数,为什么没有encode函数?

您可以像这样构建通用元组大小为 2 的编码器:

import Json.Encode exposing (..)

tuple2Encoder : (a -> Value) -> (b -> Value) -> (a, b) -> Value
tuple2Encoder enc1 enc2 (val1, val2) =
  list [ enc1 val1, enc2 val2 ]

然后你可以这样调用它,传递你想为每个插槽使用的编码器类型:

tuple2Encoder string bool ("r", False)

在 elm 0.19 https://package.elm-lang.org/packages/elm/json/latest/Json-Encode 中,通用元组 2 编码器将是

import Json.Encode exposing (list, Value)
tuple2Encoder : ( a -> Value ) -> ( b -> Value ) -> ( a, b ) -> Value
tuple2Encoder enc1 enc2 ( val1, val2 ) =
    list identity [ enc1 val1, enc2 val2 ]

用法:

encode 0 <| tuple2Encoder string int ("1",2)