假设有这样的记录:
data Place = Place
{ details :: PlaceDetails
, amenities :: [Amenity]
, photos :: [PlacePhoto]
} deriving (Generic)现在,它是这样的:
instance ToJSON Place where
toEncoding Place{..} =
pairs $ "details" .= details
<> "amenities" .= amenities
<> "photos" .= photos我使用toEncoding来保存我想要的特定顺序。但是,我想从编码中删除details键,以便PlaceDetails中所有字段与amenities和photos处于同一级别,而无需手动指定所有这些字段,因为PlaceDetails非常大。我该怎么做呢?我知道我可以用HML.unions合并[Value],但我只用toJSON做了这件事,而不是toEncoding。
我目前所拥有的:
{
"details": {
"id": "place_6de6cda0f8524a6f9c264c84afdbadad",
"name":"somename",
"description":"some description",
"other": "a lot more fields"
}
"amenities": []
"photos": []
}这就是我想要的:
{
"id":"place_6de6cda0f8524a6f9c264c84afdbadad",
"name":"somename",
"description":"some description",
"other": "a lot more fields",
"amenities": []
"photos": []
}谢谢。
发布于 2020-02-08 01:07:02
一个Aeson对象只是一个哈希图,你可以使用<> (中缀)或mappend将其联合起来。
例如:
#!/usr/bin/env cabal
{- cabal:
build-depends: base, aeson
-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE RecordWildCards #-}
module Main where
import Data.Aeson
import GHC.Generics
main :: IO ()
main = print (encode (Place (Foo 1 2) (Bar 3 4)))
data Foo = Foo {foo1 :: Int, foo2 :: Int}
deriving (Eq,Ord,Show,Generic,ToJSON)
data Bar = Bar {bar1 :: Int, bar2 :: Int}
deriving (Eq,Ord,Show,Generic,ToJSON)
data Place = Place { foo :: Foo , bar :: Bar }
deriving (Eq,Ord,Show,Generic)
instance ToJSON Place where
toJSON Place{..} =
let Object b = toJSON bar
in Object ([("foo",toJSON foo)] <> b)我们可以运行下面的代码:
% chmod +x so.hs && ./so.hs
... snippet out build info ...
"{\"bar1\":3,\"foo\":{\"foo2\":2,\"foo1\":1},\"bar2\":4}"https://stackoverflow.com/questions/60115551
复制相似问题