scala/fs2json/fs2json.sc
author Tomas Zeman <tomas@functionals.cz>
Tue, 15 Dec 2020 09:22:21 +0100
changeset 60 4267602e8494
permissions -rw-r--r--
fs2json: directory structure -> json object converter. E.g. to be used instead of erica / py-Couchapp (interaction with couchdb is left to the user).

import ammonite.ops._
import os.FileType.{Dir, File}
import ujson.{Obj, Str, Value}

import scala.collection.mutable

def fs2json(p: Path): Obj = {
  val l: Seq[(String, Value)] = ls(p) flatMap { f => f.fileType match {
    case Dir => Some(f.last -> fs2json(f))
    case File if f.last endsWith ".json" =>
      Some(f.last.dropRight(5) -> ujson.read(os.read(f)))
    case File =>
      val n = f.last.split("\\.").toList match {
        case v :: Nil => v
        case v => v dropRight 1 mkString "."
      }
      Some(n -> Str(os.read(f).stripLineEnd))
    case _ => None
  }}
  Obj(mutable.LinkedHashMap.from(l))
}

// vim: et sw=2 ts=2 syn=scala