json-extra icon indicating copy to clipboard operation
json-extra copied to clipboard

Add Json.Encode.Extra.at counterpart to Json.Decode.at

Open choonkeat opened this issue 6 years ago • 3 comments

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

choonkeat avatar Dec 06 '19 01:12 choonkeat

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"

zwilias avatar Dec 06 '19 08:12 zwilias

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 avatar Dec 06 '19 19:12 choonkeat

  • updated to use foldr 🙇
  • avoided point free style since current argument order more intuitive and matches Decode.at

choonkeat avatar Dec 07 '19 04:12 choonkeat