@@ -49,6 +49,7 @@ module Data.Aeson.Types.Instances
4949 , (.!=)
5050 , builder
5151 , series
52+ , foldable
5253 , tuple
5354 , (>*<)
5455 , typeMismatch
@@ -65,7 +66,8 @@ import Data.Scientific (Scientific)
6566import qualified Data.Scientific as Scientific (coefficient, base10Exponent, fromFloatDigits, toRealFloat)
6667import Data.Attoparsec.Number (Number(..))
6768import Data.Fixed
68−import Data.Foldable (Foldable, toList)
69+import Data.Foldable (Foldable, foldMap, toList)
70+import Data.ByteString.Builder.Prim (primBounded)
6971import Data.Functor.Identity (Identity(..))
7072import Data.Hashable (Hashable(..))
7173import Data.Int (Int8, Int16, Int32, Int64)
@@ -439,7 +441,7 @@ instance (Foldable t, ToJSON a) => ToJSON (t a) where
439441 toJSON = toJSON . toList
440442 {-# INLINE toJSON #-}
441443
442− toEncoding = E.foldable
444+ toEncoding = foldable
443445
444446instance (FromJSON a) => FromJSON (Seq.Seq a) where
445447 parseJSON = withArray "Seq a" $ traverse parseJSON . Seq.fromList . V.toList
@@ -451,6 +453,15 @@ instance (ToJSON a) => ToJSON (Vector a) where
451453
452454 toEncoding = encodeVector
453455
456+-- | Encode a 'Foldable' as a JSON array.
457+foldable :: (Foldable t, ToJSON a) => t a -> Encoding
458+foldable = brackets '[' ']' . foldMap (Value . toEncoding)
459+
460+brackets :: Char -> Char -> Series -> Encoding
461+brackets begin end (Value v) = Encoding $
462+ B.char7 begin <> fromEncoding v <> B.char7 end
463+brackets begin end Empty = Encoding (primBounded (E.ascii2 (begin,end)) ())
464+
454465encodeVector :: (ToJSON a, VG.Vector v a) => v a -> Encoding
455466encodeVector xs
456467 | VG.null xs = E.emptyArray_
@@ -511,7 +522,7 @@ instance (ToJSON a) => ToJSON (HashSet.HashSet a) where
511522 toJSON = toJSON . HashSet.toList
512523 {-# INLINE toJSON #-}
513524
514− toEncoding = E.foldable
525+ toEncoding = foldable
515526
516527instance (Eq a, Hashable a, FromJSON a) => FromJSON (HashSet.HashSet a) where
517528 parseJSON = fmap HashSet.fromList . parseJSON
@@ -571,7 +582,7 @@ encodeMap minViewWithKey foldrWithKey xs =
571582encodeWithKey :: (ToJSON k, ToJSON v) =>
572583 ((k -> v -> Series -> Series) -> Series -> m -> Series)
573584 -> m -> Encoding
574−encodeWithKey foldrWithKey = E.series '{' '}' . foldrWithKey go mempty
585+encodeWithKey foldrWithKey = brackets '{' '}' . foldrWithKey go mempty
575586 where go k v c = Value (Encoding $ encodePair k v) <> c
576587
577588encodePair :: (ToJSON k, ToJSON v) => k -> v -> B.Builder