module Hedgehog.Extras.Stock.Aeson
  ( rewriteObject
  , rewriteArrayElements
  ) where

import           Data.Aeson
import           Data.Functor
import           Data.HashMap.Lazy
import           Data.Text
import           Prelude ((.), ($))

import qualified HaskellWorks.Data.Aeson.Compat.Map as KM

-- | Rewrite a JSON object to another JSON object using the function 'f'.
--
-- All other JSON values are preserved.
rewriteObject :: (HashMap Text Value -> HashMap Text Value) -> Value -> Value
rewriteObject :: (HashMap Text Value -> HashMap Text Value) -> Value -> Value
rewriteObject HashMap Text Value -> HashMap Text Value
f (Object Object
hm) = Object -> Value
Object (forall v. HashMap Text v -> KeyMap v
KM.fromHashMapText forall b c a. (b -> c) -> (a -> b) -> a -> c
. HashMap Text Value -> HashMap Text Value
f forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall v. KeyMap v -> HashMap Text v
KM.toHashMapText forall a b. (a -> b) -> a -> b
$ Object
hm)
rewriteObject HashMap Text Value -> HashMap Text Value
_ Value
v = Value
v

-- | Rewrite each element of a JSON array using the function 'f'.
--
-- All other JSON values are preserved.
rewriteArrayElements :: (Value -> Value) -> Value -> Value
rewriteArrayElements :: (Value -> Value) -> Value -> Value
rewriteArrayElements Value -> Value
f (Array Array
hm) = Array -> Value
Array (forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Value -> Value
f Array
hm)
rewriteArrayElements Value -> Value
_ Value
v = Value
v