【问题标题】:Using Elm Json.Decode to move vales from parent to child record使用 Elm Json.Decode 将值从父记录移动到子记录
【发布时间】:2018-06-19 19:34:02
【问题描述】:

我正在编写一个 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 对象

【问题讨论】:

    标签: elm


    【解决方案1】:

    您可以在此处使用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 } }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多