Filter an object array to modify json with circe

739 views Asked by At

I am evaluating Circe and couldn't find out how to use filter for arrays to transform a JSON. I read the guide on its website and API doc, still no clue. Help much appreciated.

Sample data:

{
 "Department" : "HR",
 "Employees" :[{ "name": "abc", "age": 25 }, {"name":"def", "age" : 30 }]
}

Task:

How to use a filter for Employees to transform the JSON to another JSON, for example, all employees with age older than 50?

For some reason I can't filter from data source before JSON is generated, in case you ask.

Thanks

1

There are 1 answers

0
pathed On

One possible way of doing this is by

val data = """{"Department" : "HR","Employees" :[{ "name": "abc", "age": 25 }, {"name":"def", "age":30}]}"""

def ageFilter(j:Json): Json = j.withArray { x =>
  Json.fromValues(x.filter(_.hcursor.downField("age").as[Int].map(_ > 26).getOrElse(false)))
}
val y: Either[ParsingFailure, Json] = parse(data).map( _.hcursor.downField("Employees").withFocus(ageFilter).top.get)

println(s"$y")