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

使用Elm Json.Decode将值从父记录移动到子记录,elm,Elm,我正在编写一个elm json解码器,希望将一个值从“父”记录移动到“子”记录中 在本例中,我想将beta键/值移动到栏中 我的传入JSON { "alpha": 1, "beta: 2, "bar": { "gamma": 3 } } 我的类型 type alias Foo = { alpha : Int , bar : Bar } type alias Bar = { beta : Int , gamma : Int } 我如何在解码

我正在编写一个elm json解码器,希望将一个值从“父”记录移动到“子”记录中

在本例中,我想将
beta
键/值移动到
栏中

我的传入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对象

您可以使用
JSON.Decode.and
在这里解析
“beta”
,然后将其传递到
barDecode
JSON.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
  }
}
    """

您可以使用
Json.Decode.然后
在此处解析
“beta”
,然后将其传递到
barDecode
Json.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
  }
}
    """