json-extra
json-extra copied to clipboard
Add Json.Encode.Extra.at counterpart to Json.Decode.at
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"}}
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"
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
- updated to use foldr 🙇
- avoided point free style since current argument order more intuitive and matches
Decode.at