Search code examples
scaladictionaryplay-json

Read json key value but ignore object


I have the below json

"atrr": {
     "data": {
          "id": "asfasfsaf",
          "name": "cal",
          "type": "state"
          "ref": [
            "xyz",
            "uhz",
            "arz"
          ]
        }
}

I am reading this as below but not getting value k,v

def getData: Map[String, String] = (atrr \ "data").asOpt[Map[String, String]].getOrElse(Map[String, String]())

without ref it works fine.how do I ignore ref[] from json in code that is an object


Solution

  • You can use a custom Reads[Map[String, String]], passed to the .as or .asOpt method. My approach is to use Reads.optionNoError[String] to handle the values inside the main atrr object, so that any non-string field which would have caused an error will instead be treated as a None.

    // explicitly construct something that'd normally be constructed implicitly
    val customReads: Reads[Map[String, Option[String]] = 
      Reads.map(Reads.optionNoError[String])
    
    // pass the custom reads explicitly with parens,
    // instead of passing the expect type in square brackets
    (atrr \ "data").asOpt(customReads)
    

    This results in

    Some(
      Map(
        id -> Some(asfasfsaf), 
        name -> Some(cal), 
        type -> Some(state), 
        ref -> None
      )
    )
    

    which you can transform how you see fit, for example by doing

    .map(_.collect { case (k, Some(v)) => k -> v })