scalajson4s

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.


Solution

  • 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)