@@ -70,13 +70,16 @@ import qualified Data.Vector as V (toList)
70
70
data PState = PState { pstIndent :: Int
71
71
, pstLevel :: Int
72
72
, pstSort :: [(Text , Value )] -> [(Text , Value )]
73
+ , pstNullValues :: Bool
73
74
}
74
75
75
76
data Config = Config
76
77
{ confIndent :: Int
77
78
-- ^ Indentation spaces per level of nesting
78
79
, confCompare :: Text -> Text -> Ordering
79
80
-- ^ 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'>
80
83
}
81
84
82
85
-- | Sort keys by their order of appearance in the argument list.
@@ -94,7 +97,7 @@ keyOrder ks = comparing $ \k -> fromMaybe maxBound (elemIndex k ks)
94
97
--
95
98
-- > defConfig = Config { confIndent = 4, confCompare = mempty }
96
99
defConfig :: Config
97
- defConfig = Config { confIndent = 4 , confCompare = mempty }
100
+ defConfig = Config { confIndent = 4 , confCompare = mempty , confNullValues = True }
98
101
99
102
-- | A drop-in replacement for aeson's 'Aeson.encode' function, producing
100
103
-- JSON-ByteStrings for human readers.
@@ -120,15 +123,19 @@ encodePrettyToTextBuilder = encodePrettyToTextBuilder' defConfig
120
123
encodePrettyToTextBuilder' :: ToJSON a => Config -> a -> Builder
121
124
encodePrettyToTextBuilder' Config {.. } = fromValue st . toJSON
122
125
where
123
- st = PState confIndent 0 condSort
126
+ st = PState confIndent 0 condSort confNullValues
124
127
condSort = sortBy (confCompare `on` fst )
125
128
126
129
127
130
fromValue :: PState -> Value -> Builder
128
131
fromValue st@ PState {.. } = go
129
132
where
130
133
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
132
139
go v = Aeson. encodeToTextBuilder v
133
140
134
141
fromCompound :: PState
0 commit comments