-----------------------------------------------------------------------------
--
-- Module      :  Data.Aeson.Util
-- Copyright   :  (c) 2012-16 Brian W Bush
-- License     :  MIT
--
-- Maintainer  :  Brian W Bush <consult@brianwbush.info>
-- Stability   :  Stable
-- Portability :  Portable
--
-- | Utilities related to the <https://hackage.haskell.org/package/aeson aeson> package.
--
-----------------------------------------------------------------------------


module Data.Aeson.Util (
-- * Utilities
  extractMaybe
, extract
) where


import Data.Aeson.Types (FromJSON(..), Value, (.:), parseMaybe, withObject)
import Data.Maybe (fromJust)
import Data.Text (pack)


-- | Extract a value.
extractMaybe :: FromJSON a
             => String  -- ^ The object key.
             -> Value   -- ^ The object from which to extract the value.
             -> Maybe a -- ^ The value.
extractMaybe label = parseMaybe (withObject ("extract " ++ label) (.: pack label))


-- | Extract a value.
extract :: FromJSON a
        => String -- ^ The object key.
        -> Value  -- ^ The object from which to extract the value.
        -> a      -- ^ The value.
extract = (fromJust .) . extractMaybe