Search code examples
scalaplay-json

scala parse json objects in order


I have this following json input where I am trying to parse the name field in-order

scala> result
res6: play.api.libs.json.JsValue = {"L0": 
{"name":"FASHION","id":"50000"},"L1":{"name":"ACCESSORIES AND TRAVEL","id":"51000"},"L2":{"name":"FASHION ACCESSORIES","id":"51001"},"L3":{"name":"MENS FASHION ACCESSORIES","id":"51100"},"L4":{"name":"MENS HATS","id":"51204"}}

scala> result \\ "name"
res5: Seq[play.api.libs.json.JsValue] = List("ACCESSORIES AND TRAVEL", "MENS HATS", "MENS FASHION ACCESSORIES", "FASHION ACCESSORIES", "FASHION")

What I am trying is to get those names in-order like

List("FASHION", "ACCESSORIES AND TRAVEL", "FASHION ACCESSORIES", "MENS FASHION ACCESSORIES", "MENS HATS")

Is there a way to achieve that with play Json library?


Solution

  • With Play JSON I always use case classes. So your example would look like:

    import play.api.libs.json._

    val json = """{"L0": 
    {"name":"FASHION","id":"50000"},"L1":{"name":"ACCESSORIES AND TRAVEL","id":"51000"},"L2":{"name":"FASHION ACCESSORIES","id":"51001"},"L3":{"name":"MENS FASHION ACCESSORIES","id":"51100"},"L4":{"name":"MENS HATS","id":"51204"}}
    """
    
    case class Element(id: String, name: String)
    object Element {
      implicit val jsonFormat: Format[Element] = Json.format[Element]
    }
    
    Json.parse(json).validate[Map[String, Element]] match {
      case JsSuccess(elems, _) => println(elems.toList.sortBy(_._1).map(e => e._2.name))
      case other => println(s"Handle exception $other")
    }
    

    What this gives you, is that you can sort the result by the key - the info that is lost in your solution.