Haskell, Aeson - no instance for (ToJSON ByteStrin

2019-07-12 19:46发布

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条回答
小情绪 Triste *
2楼-- · 2019-07-12 20:18

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:

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

查看更多
登录 后发表回答