Search code examples
scalacirce

Circe Extract List from JSON


I have the following, which fails (0 did not equal 3) and I don't know why. Any thoughts?

class Temp extends MyCirceExtendingClass {
  def temp(json: Json) = {
    root.otherNames.each.otherName.string.getAll(json)
  }
}

val json = Json.fromString(
  s"""
     |{
     |    id: 1,
     |    name: "Robert",
     |    isEmployee: false,
     |    otherNames: [
     |        {
     |            id: 1,
     |            otherName: "Rob"
     |        },
     |        {
     |            id: 2,
     |            otherName: "Bob"
     |        },
     |        {
     |            id: 3,
     |            otherName: "Robby"
     |        }
     |
     |    ]
     |}
     """.stripMargin)

val response = new Temp().temp(json)
response.size shouldEqual 3

Solution

  • First, Json.fromString doesn't parse the argument, only wraps it into a Json. Second, your Json string is malformed: field names must be in quotes. After you fix these things, your lens gives correct result:

    import cats.implicits._
    import io.circe.optics.JsonPath.root
    import io.circe.parser.parse
    import io.circe.Json
    
    val json = parse(
      s"""
         |{
         |    "id": 1,
         |    "name": "Robert",
         |    "isEmployee": false,
         |    "otherNames": [
         |        {
         |            "id": 1,
         |            "otherName": "Rob"
         |        },
         |        {
         |            "id": 2,
         |            "otherName": "Bob"
         |        },
         |        {
         |            "id": 3,
         |            "otherName": "Robby"
         |        }
         |
         |    ]
         |}
     """.stripMargin).getOrElse(Json.Null)
    
    root.otherNames.each.otherName.string.getAll(json)
    
    res1: List[String] = List(Rob, Bob, Robby)