1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

scalaでxmlをjsonへ変換する

Posted at

問題

xmlでとってきたRSSをjsonに変換して扱いを楽にしたい。

解決

scalaライブラリjson4sを使うと、かなり簡単にxmlをJson形式へ変換できます。

準備は、build.sbtへjson4s-xmlを追加するだけ。

libraryDependencies += "org.json4s" %% "json4s-xml" % "3.6.3"

xmlをjsonへ変換します。
正確には、scalaのxmlを扱う標準クラスであるscala.xml.Elem型からJValueへの変換をします。

main.scala
package json

import org.json4s.JValue
import org.json4s.Xml.toJson

import scala.xml.Elem

object ScalaXml extends App {
  val xml: Elem =
    <body>
      <h1>title</h1>
      <div>
        <p>content</p>
      </div>
    </body>

  val json: JValue = toJson(xml)

  println(json) // => JObject(List((body,JObject(List((h1,JString(title)), (div,JObject(List((p,JString(content))))))))))
}

JValue形式をjsonの文字列にしたり、値の取り出しなどしたい場合は、Json4sをご参照ください。
json4s/json4s: A single AST to be used by other scala json libraries

余談

今回この問題に取り組んで、初めてscalaのxmlリテラルについて知りました。JSXと同じようにコード内にhtmlを直書きできます。
intellijのReformat Codeできれいにインデントしてくれて見やすく便利ですね。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?