title: Check or find if a particular path exists in json using play framework and scala
body: <p>I am trying to parse a json using play framework into a case class. My intention here is to check whether a particular path exists in the json. If exists then only read element at that path.</p>
  
  <p>Here is my code</p>
  
  <pre><code>package com.learning.avinash.query
  
  import play.api.libs.json.{JsDefined, JsPath, Json, Reads, Writes, __}
  import play.api.libs.functional.syntax._
  
  object ParseJson extends App {
  
    case class Msisdn(primaryId: Option[String], relatedAccountId: Option[String])
  
    object Msisdn {
      implicit val readData: Reads[Msisdn] = (
        (JsPath \ "primary-id").readNullable[String] ~
        (JsPath \ "meta" \ "related-account-id").readNullable[String]
        ) (Msisdn.apply _)
    }
  
  
  
  val testJson = """{
    "resources": [
      {
      "valid-for-start-datetime": "2019-08-23T10:47:17.485Z",
      "primary-id": "393823468684",
        "meta": {
          "related-account-id": "10001771",
              "roles": [
                "customer"
              ]
          }
      },
    {
      "valid-for-start-datetime": "2019-08-23T10:47:17.485Z",
      "primary-id": "393823467689"
      }
    ]
  }"""
      println((Json.parse(testJson) \ "resources").as[List[Msisdn]])
  }
  </code></pre>
  
  <p>In the resources array in the second object you can observe this code is completely missing</p>
  
  <pre><code>"meta": {
              "related-account-id": "10001771",
                  "roles": [
                    "customer"
                  ]
              }
  </code></pre>
  
  <p>Now when i try to parse the json, it fails and i get the following exception</p>
  
  <pre><code>Exception in thread "main" play.api.libs.json.JsResultException: JsResultException(errors:List(((1)/meta/related-accoount-id,List(JsonValidationError(List(error.path.missing),WrappedArray())))))
  </code></pre>
  
  <p>Is there a predefined function/method in play so that i can check whether this </p>
  
  <pre><code>(JsPath \ "meta")
  </code></pre>
  
  <p>particular path exists and then only read the element in that path.
  Or should i write a custom function to check whether the path exists.</p>
  
  <p>I could see a JsDefined() which expects a Jsvalue.</p>
  
  <p><a href="https://www.playframework.com/documentation/2.7.x/api/scala/play/api/libs/json/index.html" rel="nofollow noreferrer">https://www.playframework.com/documentation/2.7.x/api/scala/play/api/libs/json/index.html</a></p>
  
  <pre><code>final case classJsDefined(value: JsValue)
  Wrapper for JsValue to represent an existing Json value.
  </code></pre>
  
  <p>Any thoughts, ideas, help or suggestions please.</p>