Search code examples
jsonscalacirce

How to parse a Json array within a field while only getting certain fields of the object


I'm having some trouble using circe for a more complex extraction. If I have the below Json:

{
  "data": [
    {"a": "a-string", "b": "a-string", "c": "a-string"},
    {"a": "a-string", "b": "a-string", "c": "a-string"},
    {"a": "a-string", "b": "a-string", "c": "a-string"}
  ]
}

How could I use circe to get a list of those objects, but only containing the a and b fields?


Solution

  • Try defining a model which contains only a and b fields like so

    case class Element(a: String, b: String)
    

    For example,

    import io.circe.generic.auto._
    import io.circe.parser._
    
    case class Element(a: String, b: String)
    case class Data(data: List[Element])
    
    val raw = """{"data": [{"a": "a-string", "b": "a-string", "c": "a-string"},{"a": "a-string", "b": "a-string", "c": "a-string"}, {"a": "a-string", "b": "a-string", "c": "a-string"}] }"""
    decode[Data](raw).getOrElse(throw new RuntimeException)
    

    outputs

    res0: Data = Data(List(Element(a-string,a-string), Element(a-string,a-string), Element(a-string,a-string)))