JsLookup on multiple level array using play Json library (or any other suggestion)

622 views Asked by At

My function is receiving a JsValue, now this json have lists, and this lists element could also be lists, for example:

{
  "firstName": "Elon",
  "lastName": "Musk",
  "companies": [
    {
      "name": "Tesla",
      "city": "San Francisco",
      "offices": ["sf", "ny"],
      "management": {
        "loscation": "New York",
        "boardMembers": [
          {
            "name": "John",
            "age": 45
          },
          {
            "name": "Mike",
            "age": 55
          },
          {
            "name": "Rebecca",
            "age": 35
          }
        ]
      }
    },
    {
      "name": "SpaceX",
      "city": "San Francisco",
      "offices": ["la", "ta"],
      "management": {
        "loscation": "San Mateo",
        "boardMembers": [
          {
            "name": "Lisa",
            "age": 45
          },
          {
            "name": "Dan",
            "age": 55
          },
          {
            "name": "Henry",
            "age": 35
          }
        ]
      }
    }
  ]
}

So a company have management object, which have boardMembers list.

My function is receiving the path to this element, for example:

companies[*].management.boardMembers[*].name

I want it to return a list with all the elements of this object, so the result will be:

["John", "Mike", "Rebecca", "Lisa", "Dan", "Henry"]

It's a bit complicated, but I thought maybe play.api.libs.json._ would have some feature that could help.

thought about splitting it pathStr.split("(\\[\\*]\\.|\\[\\*])").toList and then iterate to get all elements some how and return JsLookupResult but not sure how.

Just to clarify:

My method will receive 2 parameters, the JsValue and the path as string def myFunc(json: JsValue, path: String)

every time I call myFunc it can receive different path, I'm not sure what it will be only after myFunc was called.

2

There are 2 answers

5
Tomer Shetah On BEST ANSWER

You can do:

val jsPath = JsPath \ "companies" \\ "management" \ "boardMembers" \\ "name"
val result = jsPath(Json.parse(input))
println(result)

Which will print the expected output. See Scastie example.

Please note the difference between \ and \\:

  • \ looks for direct children
  • \\ looks for recursive children

To implement myFunc you can try something like this:

def findAllValuesAtPath(jsValue: JsValue, path: String): List[JsValue] = {
  val jsPath = JsPath(path
    .split("\\[\\*]\\.")
    .flatMap(s => s.split("\\.")
      .map(RecursiveSearch)
    ).toList)
  println(jsPath.path)
  jsPath(jsValue)
}

Here is another scastie.

6
cchantep On

As you can see in the documentation, you can use the Reads typeclass to define the way to decode types from JSON.

import play.api.libs.json._

val input = """{
  "firstName": "Elon",
  "lastName": "Musk",
  "companies": [
    {
      "name": "Tesla",
      "city": "San Francisco",
      "offices": ["sf","ny"],
      "management": {
        "loscation": "New York",
        "boardMembers": [
          {
            "name": "John",
            "age": 45
          },
          {
            "name": "Mike",
            "age": 55
          },
          {
            "name": "Rebecca",
            "age": 35
          }
        ]
      }
    },
    {
      "name": "SpaceX",
      "city": "San Francisco",
      "offices": ["la","ta"],
      "management": {
        "loscation": "San Mateo",
        "boardMembers": [
          {
            "name": "Lisa",
            "age": 45
          },
          {
            "name": "Dan",
            "age": 55
          },
          {
            "name": "Henry",
            "age": 35
          }
        ]
      }
    }
  ]
}"""

val json = Json.parse(input)

// ---

case class BoardMember(name: String, age: Int)

implicit val br: Reads[BoardMember] = Json.reads

case class Company(boardMembers: Seq[BoardMember])

implicit val cr: Reads[Company] = Reads {
  case obj @ JsObject(_) =>
    (obj \ "management" \ "boardMembers").validate[Seq[BoardMember]].map {
      Company(_)
    }

  case _ =>
    JsError("error.obj.expected")
}

val reads = Reads[Seq[String]] {
  case obj @ JsObject(_) =>
    (obj \ "companies").validate[Seq[Company]].map {
      _.flatMap(_.boardMembers.map(_.name))
    }

  case _ =>
    JsError("error.obj.expected")
}

// ---

json.validate(reads)
//  play.api.libs.json.JsResult[Seq[String]] = JsSuccess(Vector(John, Mike, Rebecca, Lisa, Dan, Henry),)