简体   繁体   中英

Scala & json4s: How do I filter a json array

Array example:

[
  {
    "name": "John"
  },
  {
    "name": "Joseph"
  },
  {
    "name": "Peter"
  }
]

I'd like to filter off objects with names which are not starting with Jo :

[
  {
    "name": "John"
  },
  {
    "name": "Joseph"
  }
]

The result might be a String or JValue with json array inside.

I was not able to find a direct JSON query mechanism in json4s hence created a case class. Mappd the JSON -> filtered it -> wrote it back to JSON

import org.json4s.jackson.JsonMethods.parse
import org.json4s.jackson.Serialization
import org.json4s.native.Serialization.write
import org.json4s.{Formats, ShortTypeHints}
object JsonFIlter {
  def main(args: Array[String]): Unit = {
    implicit val formats: AnyRef with Formats = Serialization.formats(ShortTypeHints(List(classOf[PersonInfo])))
    val parseJson :List[PersonInfo] = parse("""[
                                              |  {
                                              |    "name": "John"
                                              |  },
                                              |  {
                                              |    "name": "Joseph"
                                              |  },
                                              |  {
                                              |    "name": "Peter"
                                              |  }
                                              |]""".stripMargin)
      .extract[List[PersonInfo]]
    val output = write(parseJson.filter(p => p.name.startsWith("Jo")))
    println(output)

  }

}

case class PersonInfo(name: String)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM