Haskell, Aeson - no instance for (ToJSON ByteString)

不羁岁月 提交于 2019-12-24 01:27:29

问题


So happy making it this far, encountered a new hurdle: Got this code made to be encoded to JSON. However no matter when type I use as an instance, the compiler complains. Now I am obviously doing something wrong, but it is exactly what is in the documentation (when using DeriveGeneric obviously).

{-# LANGUAGE OverloadedStrings, DeriveGeneric #-}

import Data.Aeson
import Data.Text as T
import Data.ByteString.Lazy as B
import Data.ByteString.Lazy.Char8 as BC
import GHC.Generics

-- decode :: FromJSON a => B.ByteString -> Maybe a
-- decode' :: FromJSON a => B.ByteString -> Either String a
-- encode :: ToJSON => a -> B.ByteString

data System = System  { system :: BC.ByteString
                  , make :: BC.ByteString
                  , code :: Int
                  } deriving (Generic, Show)
instance ToJSON System
-- instance FromJSON System

platform = System { system = "FPGA"
                  , make = "Xilinx"
                  , code = 10165
                  }
encodePlatform :: BC.ByteString
encodePlatform = encode platform

Compiler output:

    • No instance for (ToJSON ByteString)
        arising from a use of ‘aeson-1.4.1.0:Data.Aeson.Types.ToJSON.$dmtoJSON’
    • In the expression:
        aeson-1.4.1.0:Data.Aeson.Types.ToJSON.$dmtoJSON @(System)
      In an equation for ‘toJSON’:
          toJSON = aeson-1.4.1.0:Data.Aeson.Types.ToJSON.$dmtoJSON @(System)
      In the instance declaration for ‘ToJSON System’
   |
17 | instance ToJSON System

回答1:


That's because there is no ByteString instance for ToJSON typeclass. Historically, it used to be present but it was removed because JSON strings should be valid unicode.

You can find more details here:

  • https://github.com/bos/aeson/issues/126
  • https://github.com/bos/aeson/commit/9ee73f303cacb8ae73b2325f2f47288522607420
  • https://github.com/bos/aeson/pull/148/files

For fixing it, I would convert it to Text type and then encode into JSON.



来源:https://stackoverflow.com/questions/53295922/haskell-aeson-no-instance-for-tojson-bytestring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!