Skip to content

Commit ee37356

Browse files
committed
Optionally suppress keys with null values
Closes #16.
1 parent 6fe70dc commit ee37356

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

Data/Aeson/Encode/Pretty.hs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,13 +70,16 @@ import qualified Data.Vector as V (toList)
7070
data PState = PState { pstIndent :: Int
7171
, pstLevel :: Int
7272
, pstSort :: [(Text, Value)] -> [(Text, Value)]
73+
, pstNullValues :: Bool
7374
}
7475

7576
data Config = Config
7677
{ confIndent :: Int
7778
-- ^ Indentation spaces per level of nesting
7879
, confCompare :: Text -> Text -> Ordering
7980
-- ^ Function used to sort keys in objects
81+
, confNullValues :: Bool
82+
-- ^ Suppress object pairs with null values. Compare to <http://hackage.haskell.org/package/aeson/docs/Data-Aeson-TH.html#v:omitNothingFields 'omitNothingFields'>
8083
}
8184

8285
-- |Sort keys by their order of appearance in the argument list.
@@ -94,7 +97,7 @@ keyOrder ks = comparing $ \k -> fromMaybe maxBound (elemIndex k ks)
9497
--
9598
-- > defConfig = Config { confIndent = 4, confCompare = mempty }
9699
defConfig :: Config
97-
defConfig = Config { confIndent = 4, confCompare = mempty }
100+
defConfig = Config { confIndent = 4, confCompare = mempty, confNullValues = True }
98101

99102
-- |A drop-in replacement for aeson's 'Aeson.encode' function, producing
100103
-- JSON-ByteStrings for human readers.
@@ -120,15 +123,19 @@ encodePrettyToTextBuilder = encodePrettyToTextBuilder' defConfig
120123
encodePrettyToTextBuilder' :: ToJSON a => Config -> a -> Builder
121124
encodePrettyToTextBuilder' Config{..} = fromValue st . toJSON
122125
where
123-
st = PState confIndent 0 condSort
126+
st = PState confIndent 0 condSort confNullValues
124127
condSort = sortBy (confCompare `on` fst)
125128

126129

127130
fromValue :: PState -> Value -> Builder
128131
fromValue st@PState{..} = go
129132
where
130133
go (Array v) = fromCompound st ("[","]") fromValue (V.toList v)
131-
go (Object m) = fromCompound st ("{","}") fromPair (pstSort (H.toList m))
134+
go (Object m) = fromCompound st ("{","}") fromPair (pstSort filtered_pairs)
135+
where original_pairs = H.toList m
136+
filtered_pairs = if pstNullValues
137+
then original_pairs
138+
else filter (\(_, v) -> v /= Null) original_pairs
132139
go v = Aeson.encodeToTextBuilder v
133140

134141
fromCompound :: PState

0 commit comments

Comments
 (0)