Skip to content

Instantly share code, notes, and snippets.

@lgastako
Last active October 9, 2020 04:06
Show Gist options
  • Save lgastako/9271a76116d8afed616de442a384a0c0 to your computer and use it in GitHub Desktop.
Save lgastako/9271a76116d8afed616de442a384a0c0 to your computer and use it in GitHub Desktop.
{-# LANGUAGE OverloadedStrings #-}
module GetIn where
import Data.Aeson ( Value( Array
, Null
, Object
)
, decode
)
import Data.HashMap.Strict ( lookupDefault )
import Data.List ( foldl' )
import Data.Maybe ( fromMaybe )
import Data.Text ( Text
, unpack
)
import Data.Vector ( (!?) )
import Text.Read ( readMaybe )
getIn :: [Text] -> Value -> Value
getIn = flip . foldl' $ \v k -> case v of
Object m -> lookupDefault Null k m
Array a -> maybe Null (fromMaybe Null . (a !?)) . readMaybe . unpack $ k
_ -> Null
example :: Value
example = fromMaybe (error "boom") . decode
$ "{\"a\":{\"b\":{\"c\":[\"foo\",\"bar\",\"baz\"]}}}"
example2 :: Value
example2 = fromMaybe (error "boom") . decode
$ "{\"a\":{\"b\":{\"c\":[\"foo\",{\"d\":7},\"baz\"]}}}"
-- λ> getIn ["a", "b", "c"] example
-- Array [String "foo",String "bar",String "baz"]
-- λ> getIn ["a", "b", "c", "1"] example
-- String "bar"
-- λ> getIn ["a", "b", "c", "1", "d"] example2
-- Number 7.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment