【问题标题】:Is it possible to match a changing JSON key to a sum type data constructor with aeson inside a larger record type?是否可以将更改的 JSON 键与较大记录类型中的 aeson 与 sum 类型数据构造函数相匹配?
【发布时间】:2020-08-10 23:04:40
【问题描述】:

所以我有这个数据类型ItemType,它是使用它的数据构造函数名称解码的(参见 FromJSON 实例)。

import           Data.Aeson
import           Data.Aeson.Types
import           Data.Char (toLower)
import           GHC.Generics

data ItemType =
    MkLogin Login
  | MkCard Card
  | MkIdentity Identity
  | MkSecureNote Note
  deriving (Generic, Show)

lowercase :: String -> String
lowercase "" = ""
lowercase (s:ss) = toLower s : ss

stripPrefix :: String -> String
stripPrefix ('M':'k':ss) = ss
stripPrefix str = str

-- | Decode value using ItemType data constructor names
instance FromJSON ItemType where
  parseJSON = genericParseJSON defaultOptions
    { constructorTagModifier = lowercase . stripPrefix
    , sumEncoding = ObjectWithSingleField }

我想要做的是将此类型作为一个字段添加到一个名为Item的更大记录类型中

data Item =
  Item { _object :: String
       , _id :: String
       , _organizationId :: Maybe Int
       , _folderId :: Maybe Int
       , _type :: Int
       , _name :: String
       , _notes :: String
       , _favorite :: Bool
       , ??? :: ItemType -- don't know how to add this without a different field name
       , _collectionIds :: [Int]
       , _revisionDate :: Maybe String
       } deriving (Generic, Show)

instance FromJSON Item where
  parseJSON =
    genericParseJSON defaultOptions { fieldLabelModifier = stripUnderscore }

但是我不想为该类型创建一个新的字段名称。相反,我想使用 aeson 在ItemType 上匹配的数据构造函数作为字段名称,因为我试图建模的 JSON 对象中 ItemType 字段的键取决于 ItemType 它是什么而变化。所以在这种情况下,密钥是“login”、“card”、“identity”、“secureNote”。也许我应该将TaggedObject 用于sumEncoding,但我不完全确定它是如何工作的。

Item 对象的示例 JSON 列表:https://i.imgur.com/xzHy9MU.png。在这里,您可以通过“登录”、“卡片”、“身份”等键查看ItemType 字段,具体取决于它们的类型。

【问题讨论】:

    标签: parsing haskell aeson


    【解决方案1】:

    您可以使用相当丑陋的 hack 来预处理传入的 JSON Value,以便实际的 JSON 输入如下:

    {
      "id": "foo",
      "bool": false
    }
    

    被解析为:

    {
      "id": "foo",
      "itemtype": {"bool" : false}
    }
    

    可以由通用解析器使用ObjectWithSingleField sum 编码方法直接处理。

    作为一个简化的例子,给定:

    data ItemType =
        MkInt Int
      | MkBool Bool
      deriving (Generic, Show)
    
    instance FromJSON ItemType where
      parseJSON = genericParseJSON defaultOptions
        { constructorTagModifier = map toLower . \('M':'k':ss) -> ss
        , sumEncoding = ObjectWithSingleField }
    

    和:

    data Item =
      Item { _id :: String
           , _itemtype :: ItemType
           }
      deriving (Generic, Show)
    

    您可以为Item 编写一个FromJSON 实例,该实例将"int" 或"bool" 字段嵌套在"itemtype" 字段内。 (原始字段的副本保留在原地,但被通用解析器忽略。)

    instance FromJSON Item where
      parseJSON v = do
        v' <- withObject "Item" nest v
        genericParseJSON defaultOptions { fieldLabelModifier = \('_':ss) -> ss } v'
        where nest o = Object <$> (HM.insert "itemtype" <$> item <*> pure o)
                where item = subObj "int" <|> subObj "bool" <|> fail "no item type field"
                      subObj k = (\v -> object [(k,v)]) <$> o .: k
    

    完整代码:

    {-# LANGUAGE DeriveGeneric #-}
    {-# LANGUAGE OverloadedStrings #-}
    {-# LANGUAGE TupleSections #-}
    
    import           Control.Applicative
    import           Data.Aeson
    import           Data.Aeson.Types
    import           Data.Char (toLower)
    import           GHC.Generics
    import qualified Data.HashMap.Strict as HM
    
    data ItemType =
        MkInt Int
      | MkBool Bool
      deriving (Generic, Show)
    
    instance FromJSON ItemType where
      parseJSON = genericParseJSON defaultOptions
        { constructorTagModifier = map toLower . \('M':'k':ss) -> ss
        , sumEncoding = ObjectWithSingleField }
    
    data Item =
      Item { _id :: String
           , _itemtype :: ItemType
           }
      deriving (Generic, Show)
    
    instance FromJSON Item where
      parseJSON v = do
        v' <- withObject "Item" nest v
        genericParseJSON defaultOptions { fieldLabelModifier = \('_':ss) -> ss } v'
        where nest o = Object <$> (HM.insert "itemtype" <$> item <*> pure o)
                where item = subObj "int" <|> subObj "bool" <|> fail "no item type field"
                      subObj k = (\v -> object [(k,v)]) <$> o .: k
    
    test1, test2, test3 :: Either String Item
    test1 = eitherDecode "{\"id\":\"foo\",\"bool\":false}"
    test2 = eitherDecode "{\"id\":\"foo\",\"int\":10}"
    test3 = eitherDecode "{\"id\":\"foo\"}"
    
    main = do
      print test1
      print test2
      print test3
    

    不过,一般来说,除非您经常这样做,否则为了清晰和可读性,放弃泛型并编写必要的样板文件可能会更好。即使对于您的原始示例,它也不是那么繁重。是的,您必须使类型和实例保持同步,但是一些简单的测试应该可以发现任何问题。因此,例如,类似:

    instance FromJSON Item where
      parseJSON = withObject "Item" $ \o ->
        Item <$> o .: "object"
             <*> o .: "id"
             <*> o .:? "organizationId"
             <*> o .:? "folderId"
             <*> o .: "type"
             <*> o .: "name"
             <*> o .: "notes"
             <*> o .: "favorite"
             <*> parseItemType o
             <*> o .: "collectionIds"
             <*> o .:? "revisionDate"
        where parseItemType o =
                    MkLogin <$> o .: "login"
                <|> MkCard <$> o .: "card"
                <|> MkIdentity <$> o .: "identity"
                <|> MkSecureNote <$> o .: "securenote"
    

    【讨论】:

      【解决方案2】:

      一种方法是在 Item 数据声明中完全没有 ItemType 的字段。然后使用元组或自定义对类型来保存这两个部分;所以:

      data ItemWithType = ItemWithType ItemType Item
      
      instance FromJSON ItemWithType where
          parseJSON v = liftA2 ItemWithType (parseJSON v) (parseJSON v)
      

      你也可以跳过定义ItemWithType而直接使用

      \o -> liftA2 (,) (parseJSON o) (parseJSON o)
      

      直接解析一个名称一致的字段和变量key下的对象的元组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多