Skip to content

Instantly share code, notes, and snippets.

@piyo7
Created March 1, 2015 09:24
Show Gist options
  • Select an option

  • Save piyo7/7fd0e9c36842e658f64f to your computer and use it in GitHub Desktop.

Select an option

Save piyo7/7fd0e9c36842e658f64f to your computer and use it in GitHub Desktop.
Qiita:Teamの投稿をMarkdownファイルでエクスポート ref: http://qiita.com/piyo7/items/6d0a831b1fb90392f485
sbt.version=0.13.7
name := "splitQiitaTeamJson"
version := "1.0"
scalaVersion := "2.11.4"
libraryDependencies += "org.json4s" %% "json4s-native" % "3.2.11"
> tree /F
├─piyo7
│ boost__optionalにモナドのbindを.md
│ ICML 2014 Best Paper斜め読み.md
│ Qiita_Teamの更新をChatWorkに通知する.md
...
├─piyo8
...
case class QiitaTeamUser(url_name: String)
case class QiitaTeamPost(title: String, user: QiitaTeamUser, raw_body: String)
object Main extends App {
splitQiitaTeamJson("C:\\TEMP\\123456789.json") // エクスポートしたJSONファイルのパス
def splitQiitaTeamJson(file: String) {
using(scala.io.Source.fromFile(file, "UTF-8")) { source =>
// JSONパース
implicit val formats = org.json4s.DefaultFormats
val json = org.json4s.native.JsonMethods.parse(source.mkString)
val posts = json.children.map(_.extract[QiitaTeamPost])
// Markdownファイル出力
posts.foreach { post =>
val dir = "out\\" + post.user.url_name
val file = post.title.replaceAll("[\\/:*?\"<>|]", "_") + ".md" // Windowsのパス禁止文字を置換
new java.io.File(dir).mkdirs()
writeFile(dir + "\\" + file)(_.print(post.raw_body))
}
}
// 簡易loanパターン
def using[A <: {def close() : Unit}](s: A)(f: A => Any) {
try f(s)
finally s.close()
}
def writeFile(file: String)(f: java.io.PrintWriter => Unit) {
import java.io._
try using(new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")))(f)
catch {
case e: FileNotFoundException => println(e)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment