Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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