Last active
May 8, 2017 23:32
-
-
Save bneijt/9bdb4b1759790a8463c9 to your computer and use it in GitHub Desktop.
Create json files form simple first-line image, rest description files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/runghc | |
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-} | |
import Prelude (Show, IO, (++), print, String, filter) | |
import Data.List (isSuffixOf) | |
import Data.Text hiding (isSuffixOf, filter) | |
import Data.Text.IO | |
import Control.Monad (mapM_) | |
import qualified Data.ByteString.Lazy as BL | |
import System.Directory (getDirectoryContents) | |
import System.FilePath.Posix ((<.>), FilePath, takeBaseName) | |
import Data.Aeson | |
data Product = Product | |
{ image :: Text | |
, description :: Text | |
} deriving Show | |
instance ToJSON Product where | |
toJSON (Product image description) = object ["image" .= image, "description" .= description] | |
encodeToJson :: FilePath -> IO() | |
encodeToJson srcName = do | |
let jsonName = takeBaseName srcName <.> "json" | |
contents <- readFile srcName | |
let contentLines = lines contents | |
case contentLines of -- head is unsafe! try your code on an empty file | |
(firstLine : restLines) -> BL.writeFile jsonName (encode Product { | |
image = firstLine, | |
description = unlines restLines | |
}) | |
_ -> print ("error: invalid source file: " ++ srcName) | |
main = do | |
names <- getDirectoryContents "." | |
let srcNames = filter (isSuffixOf ".src") names | |
mapM_ encodeToJson srcNames |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Python version of the same code