如何解码榆树中的空对象{}?

How to decode an empty object {} in elm?

我正在为 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,但找不到解决方案。

您可以通过使用 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"