Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading