使用Elm Json.Decode将值从父记录移动到子记录

时间:2018-06-19 19:34:02

标签: elm

我正在编写elm json解码器,并希望将值从“父”记录移至“子”。

在此示例中,我想移动beta键/值以使用Bar类型。

我的传入JSON

{ "alpha": 1,
  "beta: 2,
  "bar": {
    "gamma": 3 
  }
}

我的类型

type alias Foo =
  { alpha : Int
  , bar : Bar 
  }

type alias Bar =
  { beta : Int 
  , gamma : Int 
  }

如何在解码器中做到这一点?我觉得我想将beta的解码器传递到fooDecode。但这显然是不对的...

fooDecode =
    decode Foo
        |> required "alpha" Json.Decode.int
        |> required "bar" barDecode (Json.Decode.at "beta" Json.Decode.int)

barDecode betaDecoder =
    decode Bar
        |> betaDecoder
        |> required "gamma" Json.Decode.int

注意:我的实际用例中有一个孩子列表,但希望我可以在上面有一个指针来解决这个问题。我正在使用Decode.Pipeline,因为它是一个大型JSON对象

1 个答案:

答案 0 :(得分:5)

您可以在此处使用Json.Decode.andThen来解析"beta",然后将其传递给barDecodeJson.Decode.Pipeline.custom以使其与管道一起使用:

fooDecode : Decoder Foo
fooDecode =
    decode Foo
        |> required "alpha" Json.Decode.int
        |> custom
            (Json.Decode.field "beta" Json.Decode.int
                |> Json.Decode.andThen (\beta -> Json.Decode.field "bar" (barDecode beta))
            )


barDecode : Int -> Decoder Bar
barDecode beta =
    decode Bar
        |> hardcoded beta
        |> required "gamma" Json.Decode.int

此更改

main : Html msg
main =
    Html.text <| toString <| decodeString fooDecode <| """
{ "alpha": 1,
  "beta": 2,
  "bar": {
    "gamma": 3
  }
}
    """

打印:

Ok { alpha = 1, bar = { beta = 2, gamma = 3 } }