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 Json.Encode.Extra.at counterpart to Json.Decode.at #28

Open choonkeat opened 4 years ago

choonkeat commented 4 years ago

The standard elm/json has a nice function Json.Decode.at

Json.Decode.at [ "Nightmare", "At" ] Json.Decode.string

This PR introduces the counterpart for encoding: Json.Encode.Extra.at

encodedValue = (Json.Encode.string "Elm Street")

Json.Encode.Extra.at [ "Nightmare", "At" ] encodedValue
-- {"Nightmare":{"At":"Elm Street"}}
zwilias commented 4 years ago

Cool!

How would you feel about taking the "encoder" and the "value to be encoded" both as arguments, much in the same way Encode.list takes an a -> Encode.Value and a List a?

So, the result would be something like

at : List String -> (a -> Encode.Value) -> a -> Encode.Value
at path enc val = List.foldr (\x acc -> Encode.object [ (x, acc) ]) (enc val) path

Which would turn the example into at [ "Nightmare", "at" ] Encode.string "Elm Street"

choonkeat commented 4 years ago

Oh foldr is much better!

As for arguments, in scenarios where I have encoder & value, I could use either api inline: wrapping in parentheses for the first api.

at [ "Nightmare", "at" ] Encode.string "Elm Street"
at [ "Nightmare", "at" ] (Encode.string "Elm Street")

But if I only have an encodedValue, I’d need to pass identity into the 2nd api, a bit more unnatural?

at [ "Nightmare", "at" ] identity encodedValue
at [ "Nightmare", "at" ] encodedValue
choonkeat commented 4 years ago