Created
November 21, 2024 05:24
-
-
Save joeyadams/63c40e5efd43f9065adf25fa19e498f2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- This gist provides a function to serialize JSON with indentation. It uses the type's | |
-- toEncoding implementation, meaning it follows the property order defined by the type | |
-- when ToJSON is implemented with genericToEncoding. | |
-- | |
-- See below for an example and license information. | |
-- | |
{-# LANGUAGE DerivingVia #-} | |
{-# LANGUAGE DuplicateRecordFields #-} | |
{-# LANGUAGE NoFieldSelectors #-} | |
{-# LANGUAGE OverloadedRecordDot #-} | |
{-# LANGUAGE OverloadedStrings #-} | |
import qualified Data.Aeson as Aeson | |
import qualified Data.Aeson.Encoding as AE | |
import qualified Data.Aeson.Encoding.Internal as AE | |
import qualified Data.ByteString.Builder as BB | |
import qualified Data.ByteString.Lazy as BL | |
import qualified Data.ByteString.Lazy.Char8 as BL8 | |
import Data.Aeson (FromJSON, FromJSONKey, ToJSON, ToJSONKey, genericParseJSON, genericToEncoding) | |
import Data.Aeson.Decoding.ByteString.Lazy (lbsToTokens) | |
import Data.Aeson.Decoding.Tokens | |
import Data.ByteString.Builder (Builder) | |
import Data.ByteString.Builder.Scientific (formatScientificBuilder, FPFormat(..)) | |
import Data.Char (isSpace) | |
import Data.Semigroup (stimes) | |
import Data.Text (Text) | |
import GHC.Generics (Generic) | |
-- | Encode a value as JSON with indentation. For types using generically-derived 'ToJSON', | |
-- this follows the property order defined by the data type. | |
encodePretty :: (ToJSON a) => a -> BL.ByteString | |
encodePretty = reformatJSON . Aeson.encode | |
-- | Reformat JSON content with indentation. This will throw an error | |
-- if the given content is not valid JSON. | |
-- | |
-- This is lazy, and preserves original property ordering. It may reformat numbers, | |
-- however (e.g. \"3.00000\" to \"3.0\"). | |
reformatJSON :: BL.ByteString -> BL.ByteString | |
reformatJSON = | |
-- Decode with Data.Aeson.Decoding.Tokens, and re-encode with indentation. | |
BB.toLazyByteString . tokensToPretty . lbsToTokens | |
-- | Format tokenized JSON with indentation. | |
tokensToPretty :: Tokens BL.ByteString String -> Builder | |
tokensToPretty tokens = | |
go 0 tokens $ \leftover -> | |
if BL.null $ BL8.dropWhile isSpace leftover | |
then mempty | |
else error "Unexpected data at the end of the JSON stream" | |
where | |
go :: Int -- Indent level (number of spaces). Only applies when a line break is made. | |
-> Tokens k String -- The initial token of the value, e.g. TkRecordOpen which means "{" | |
-> (k -> Builder) -- Continuation to render whatever is after this token. | |
-> Builder | |
go _ (TkLit lit k) f = goLit lit <> f k | |
go _ (TkText txt k) f = goText txt <> f k | |
go _ (TkNumber num k) f = goNum num <> f k | |
-- For empty arrays and records, do not emit a newline. | |
go _ (TkArrayOpen (TkArrayEnd k)) f = BB.char8 '[' <> BB.char8 ']' <> f k | |
go _ (TkRecordOpen (TkRecordEnd k)) f = BB.char8 '{' <> BB.char8 '}' <> f k | |
go indent (TkArrayOpen a) f = goA '[' indent a f | |
go indent (TkRecordOpen r) f = goR '{' indent r f | |
go _ (TkErr e) _ = error e | |
goLit LitNull = AE.fromEncoding AE.null_ | |
goLit LitTrue = AE.fromEncoding (AE.bool True) | |
goLit LitFalse = AE.fromEncoding (AE.bool False) | |
goText = AE.fromEncoding . AE.text | |
goNum (NumInteger n) = BB.integerDec n | |
goNum (NumDecimal n) = formatScientificBuilder Fixed Nothing n | |
goNum (NumScientific n) = formatScientificBuilder Exponent Nothing n | |
goA :: Char -> Int -> TkArray k String -> (k -> Builder) -> Builder | |
goA sep indent (TkItem item) f = | |
let !indent' = indent + 2 | |
in BB.char8 sep <> | |
nl indent' <> | |
go indent' item (\arr -> goA ',' indent arr f) | |
goA _ indent (TkArrayEnd k) f = | |
nl indent <> | |
BB.char8 ']' <> | |
f k | |
goA _ _ (TkArrayErr e) _ = error e | |
goR :: Char -> Int -> TkRecord k String -> (k -> Builder) -> Builder | |
goR sep indent (TkPair k item) f = | |
let !indent' = indent + 2 | |
in BB.char8 sep <> | |
nl indent' <> | |
AE.fromEncoding (AE.key k) <> BB.char8 ':' <> BB.char8 ' ' <> | |
go indent' item (\arr -> goR ',' indent arr f) | |
goR _ indent (TkRecordEnd k) f = | |
nl indent <> | |
BB.char8 '}' <> | |
f k | |
goR _ _ (TkRecordErr e) _ = error e | |
nl :: Int -> Builder | |
nl count = BB.char8 '\n' <> stimes count (BB.char8 ' ') | |
-- | Simple benchmark: Read standard input and reformat as JSON. | |
-- (If you just want to reformat JSON from the command line, jq is better for this.) | |
main :: IO () | |
main = BL.getContents >>= BL8.putStrLn . reformatJSON | |
------------------------------------------------------------------------- | |
-- Example | |
newtype Id a = Id Int | |
deriving (Eq, Ord, Show, FromJSON, ToJSON, FromJSONKey, ToJSONKey) | |
via Int | |
data Widget = Widget | |
{ id :: Id Widget | |
, description :: Text | |
, parts :: [Part] | |
} | |
deriving (Generic) | |
data Part = Part | |
{ id :: Id Part | |
, name :: Text | |
, available :: Bool | |
} | |
deriving (Generic) | |
instance FromJSON Widget where | |
parseJSON = genericParseJSON Aeson.defaultOptions | |
instance ToJSON Widget where | |
toEncoding = genericToEncoding Aeson.defaultOptions | |
toJSON = toJSONViaEncoding | |
instance FromJSON Part where | |
parseJSON = genericParseJSON Aeson.defaultOptions | |
instance ToJSON Part where | |
toEncoding = genericToEncoding Aeson.defaultOptions | |
toJSON = toJSONViaEncoding | |
toJSONViaEncoding :: (ToJSON a) => a -> Aeson.Value | |
toJSONViaEncoding = either error id . Aeson.eitherDecode . AE.encodingToLazyByteString . Aeson.toEncoding | |
widgets :: [Widget] | |
widgets = | |
[ Widget | |
{ id = Id 1 | |
, description = "Basic widget" | |
, parts = | |
[ Part { id = Id 101, name = "Widget Frame", available = True } | |
, Part { id = Id 102, name = "Widget Panel", available = True } | |
] | |
} | |
, Widget | |
{ id = Id 2 | |
, description = "A thneed: something everyone needs!" | |
, parts = | |
[ Part { id = Id 201, name = "Thneed Frame", available = True } | |
, Part { id = Id 202, name = "Thneed Fabric", available = False } | |
] | |
} | |
] | |
printWidgets :: IO () | |
printWidgets = BL8.putStrLn $ encodePretty widgets | |
------------------------------------------------------------------------- | |
-- LICENSE | |
-- Copyright (c) 2024 Joseph Adams | |
-- | |
-- Permission is hereby granted, free of charge, to any person obtaining a copy | |
-- of this software and associated documentation files (the "Software"), to deal | |
-- in the Software without restriction, including without limitation the rights | |
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
-- copies of the Software, and to permit persons to whom the Software is | |
-- furnished to do so, subject to the following conditions: | |
-- | |
-- The above copyright notice and this permission notice shall be included in | |
-- all copies or substantial portions of the Software. | |
-- | |
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING | |
-- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS | |
-- IN THE SOFTWARE. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment