Open Janiczek opened 5 years ago
Alternatively, when (keyValuePairs (succeed ())) List.isEmpty (succeed ())
, though the error message is less informative.
I'm going to mull this over a little bit - I agree that it's not a super obvious trick, but I also wonder whether it's a common enough use-case ("the object must be empty") that it should be a utility here.
As a final alternative, this could also be done using https://package.elm-lang.org/packages/zwilias/json-decode-exploration/latest/Json-Decode-Exploration#isObject and strict decoding - if the object had any keys, those would result in errors. (that whole package is built around the idea that unused data in the JSON should not be ignored)
In my job, we've just encountered a situation where we need to decode an empty JSON object. There is a trick for it but not many people know it. So, let's give it a name and make it more discoverable?
EDIT: I tried to create a doctest for the
Err
case (ie.decodeString emptyObject """{"foo": "bar"}""" --> Err (Failure "..." (Json.Encode.string "...")
) but there seems to be some issue withEncode.Value
equality - couldn't make that work.