Search code examples
haskellbytestring

Using OverloadedStrings with ByteString type


I would like to input a string from the console and output a JSON string.

{-# LANGUAGE OverloadedStrings #-}

module Main where
  
import Data.Aeson
import Data.Map.Strict
                
main :: IO ()
main = interact $ encode

This code fails. Of course, I see encode has type ToJSON a => a -> Data.ByteString.Lazy.Internal.ByteString and interact' takes String -> String, but that's the reason I'm using OverloadedStrings.

How can I solve this problem ? Perform a cast to String ?


Solution

  • OverloadedStrings only works for string literals. It thus converts a "foo" expression to fromString "foo".

    But you can use this to convert this to a ByteString. You can first use decodeUtf8 :: ByteString -> Text to convert the ByteString to a Text, then use the String data constructor of the Value type, and then encode the data, so:

    module Main where

    import Data.Aeson(Value(String), encode)
    import qualified Data.ByteString as B
    import Data.ByteString.Lazy(toStrict)
    import Data.Text.Encoding(decodeUtf8)
    
    main :: IO ()
    main = B.interact (toStrict . encode . String . decodeUtf8)
    

    This will thus convert the input to a JSON string literal.