【问题标题】:How to decode an empty object {} in elm?如何解码榆树中的空对象{}?
【发布时间】:2020-02-26 23:11:42
【问题描述】:

我正在为 elm (0.19.1) 编写 JSON 解码器。我传入的 json Value 是一个空对象{}。如何将该值解码为类型(此处为 NoPayload)?

我尝试在JD.string解码器的帮助下对其进行解码:

JD.string
    |> JD.andThen
        (\str ->
            if str == "{}" then
                JD.succeed NoPayload

            else
                JD.fail "Failed to decode non-empty payload to NoPayload decoder"
        )

但这导致了一个错误:

Problem with the given value:

    {}

    Expecting a STRING

或者,我正在尝试JD.nullJD.dict,但我找不到解决方案。

【问题讨论】:

    标签: json elm


    【解决方案1】:

    您可以通过使用dict将JSON对象转换为字典来验证空对象,然后验证字典中没有键:

    import Dict
    import Json.Decode as JD exposing (Decoder)
    
    emptyJsonDecoder : Decoder Payload
    emptyJsonDecoder =
        JD.dict JD.int
            |> JD.andThen
                (\entries ->
                    case Dict.size entries of
                        0 ->
                            JD.succeed NoPayload
    
                        _ ->
                            JD.fail "Expected empty JSON object"
                )
    

    用于验证:

    JD.decodeString emptyJsonDecoder "{}"          == Ok NoPayload
    JD.decodeString emptyJsonDecoder "{\"a\":123}" == Err "Expected empty JSON object"
    

    【讨论】:

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