From bd741949aabf489a39b7fcc680522560cab0ea91 Mon Sep 17 00:00:00 2001 From: choonkeat Date: Fri, 6 Dec 2019 09:11:33 +0800 Subject: [PATCH] Add Json.Encode.Extra.at counterpart to Json.Decode.at --- src/Json/Encode/Extra.elm | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/src/Json/Encode/Extra.elm b/src/Json/Encode/Extra.elm index 44756f2..61cc590 100644 --- a/src/Json/Encode/Extra.elm +++ b/src/Json/Encode/Extra.elm @@ -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. @@ -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