Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell, Aeson - no instance for (ToJSON ByteString)

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
like image 776
Madderote Avatar asked Nov 14 '18 08:11

Madderote


1 Answers

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.

like image 102
Sibi Avatar answered Oct 18 '22 22:10

Sibi