Skip to content

Instantly share code, notes, and snippets.

@bneijt
Last active May 8, 2017 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bneijt/9bdb4b1759790a8463c9 to your computer and use it in GitHub Desktop.
Save bneijt/9bdb4b1759790a8463c9 to your computer and use it in GitHub Desktop.
Create json files form simple first-line image, rest description files
#!/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
@bneijt
Copy link
Author

bneijt commented Mar 1, 2015

Python version of the same code

#!/usr/bin/python
import os
import json

def main():
    srcFiles = [f for f in os.listdir(".") if f.endswith(".src")]
    for srcFilename in srcFiles:
        with open(srcFilename, "r") as srcFile:
            contents = srcFile.readlines()
            basename, src = os.path.splitext(srcFilename)
            with open(basename + ".json", "w") as jsonFile:
                json.dump({
                    "image": contents[0],
                    "description": " ".join(contents[1:])
                    }, jsonFile)

if __name__ == "__main__":
    main()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment