- Haskell 是否可以縮進輸出 json 檔案以使其對人類友好?
- 此選項存在于其他編程語言(如 Python)中
- 下面列出的是一個作業示例:
- 讀取輸入的 json 檔案
- 以某種方式操縱它
- 將結果存盤回另一個 json 檔案
- 唯一的麻煩是,我無法人工檢查它,因為它是一個巨大的單線
{-# LANGUAGE DeriveGeneric #-}
-- ***************
-- * *
-- * module main *
-- * *
-- ***************
module Main (main) where
-- *******************
-- * *
-- * general imports *
-- * *
-- *******************
import System.IO
import Data.Aeson
import GHC.Generics
import Control.Monad
import System.Environment
-- *****************************
-- * *
-- * general qualified imports *
-- * *
-- *****************************
import qualified Data.ByteString.Lazy as B
-- ****************************
-- * *
-- * read json file to memory *
-- * *
-- ****************************
getJSON :: IO B.ByteString
getJSON = B.readFile "input.json"
-- *********************
-- * *
-- * data type: Person *
-- * *
-- *********************
data Person =
Person
{
idnum :: Integer,
height :: Integer,
weight :: Integer
}
deriving (Show, Generic)
-- *********************
-- * *
-- * data type: Person *
-- * *
-- *********************
instance ToJSON Person
instance FromJSON Person
-- **************************
-- * *
-- * data type: AfterPerson *
-- * *
-- **************************
data AfterMarathonPerson =
AfterMarathonPerson
{
person :: Person,
weightLoss :: Integer
}
deriving (Show, Generic)
-- **************************
-- * *
-- * data type: AfterPerson *
-- * *
-- **************************
instance ToJSON AfterMarathonPerson
-- *******************
-- * *
-- * marathon effect *
-- * *
-- *******************
marathonEffect :: Person -> AfterMarathonPerson
marathonEffect (Person i h w) = AfterMarathonPerson (Person i h w) (w-23)
-- ********************
-- * *
-- * main entry point *
-- * *
-- ********************
main = do
marathon <- (eitherDecode <$> getJSON) :: IO (Either String [Person])
case marathon of
Left jsonReadError -> putStrLn jsonReadError
Right runners -> encodeFile "output.json"
$ toJSON
$ map marathonEffect
$ runners
uj5u.com熱心網友回復:
使用包中的encodePretty函式aeson-pretty生成ByteString漂亮列印的 JSON,然后將其寫入檔案,ByteString.writeFile而不是使用encodeFile.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/493305.html
下一篇:令人困惑的ReaderT定義
