How to decode an empty object {} in elm?

Viewed 393

I am writing a JSON decoder for elm (0.19.1). My incoming json Value is an empty object {}. How can I decode that value to a type (here NoPayload)?

I tried to decode it with the help of JD.string decoder:

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

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

But that resulted in an error:

Problem with the given value:

    {}

    Expecting a STRING

Alternatively, I am experimenting with JD.null and JD.dict, but I cannot find a solution.

1 Answers

You can validate an empty object by using dict to convert the JSON object to a dictionary, then validate that there are no keys in the dictionary:

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"
            )

For validation:

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