elm-community / json-extra

Convenience functions for working with Json.
http://package.elm-lang.org/packages/elm-community/json-extra/latest
MIT License
37 stars 16 forks source link

Add emptyObject #23

Open Janiczek opened 5 years ago

Janiczek commented 5 years ago

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 with Encode.Value equality - couldn't make that work.

zwilias commented 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)