Skip to content

Commit

Permalink
Add Json.Encode.Extra.at
Browse files Browse the repository at this point in the history
counterpart to Json.Decode.at
  • Loading branch information
choonkeat committed Dec 7, 2019
1 parent 8489218 commit bd74194
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion src/Json/Encode/Extra.elm
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
module Json.Encode.Extra exposing (maybe)
module Json.Encode.Extra exposing
( maybe
, at
)

{-| Convenience functions for turning Elm values into Json values.
Expand All @@ -25,3 +28,26 @@ import Json.Encode exposing (Value, encode, int, null, object)
maybe : (a -> Value) -> Maybe a -> Value
maybe encoder =
Maybe.map encoder >> Maybe.withDefault null


{-| Decode a nested JSON object, requiring certain fields.
import Json.Encode exposing (..)
encodedValue : Json.Encode.Value
encodedValue =
(Json.Encode.string "Elm Street")
at [ "Nightmare", "At" ] encodedValue
|> Json.Encode.encode 0
--> "{\"Nightmare\":{\"At\":\"Elm Street\"}}"
This is really just a shorthand for:
Json.Encode.object [ ( "Nightmare", Json.Encode.object [ ( "At", encodedValue ) ] ) ]
|> Json.Encode.encode 0
-}
at : List String -> Json.Encode.Value -> Json.Encode.Value
at keys initial =
List.foldr (\k current -> Json.Encode.object [ ( k, current ) ]) initial keys

0 comments on commit bd74194

Please sign in to comment.