Not able to access key-values pairs in a JSON using Play library in scala

586 Views Asked by At

I am using elasticsearch where as a response from the server I get a JSON. So,

val builder = new TermVectorRequestBuilder(client, "new_index", "documents", "0056").setSelectedFields("text")
builder.setTermStatistics(true).setFieldStatistics(true)
val resp: TermVectorResponse = builder.execute().actionGet()
val json_reader = XContentFactory.contentBuilder(XContentType.JSON).prettyPrint()

where json_reader is of type org.elasticsearch.common.xcontent.XContentBuilder.

Following is what json_reader looks like:

"_index""new_index",
"_type" "documents",
"_id" "0056",
"_version" 1,
"found" true,
"took" 2,
"term_vectors" {
  "text" : {
    "field_statistics" : {
      "sum_doc_freq" : 26433,
      "doc_count" : 15,
      "sum_ttf" : 29089
    },
    "terms" : {
      "11" : {
        "doc_freq" : 4,
        "ttf" : 5,
        "term_freq" : 1,
        "tokens" : [ {
          "position" : 306,
          "start_offset" : 1791,
          "end_offset" : 1793
        } ]
      },
      "11 30" : {
        "doc_freq" : 1,
        "ttf" : 1,
        "term_freq" : 1,
        "tokens" : [ {
          "position" : 306,
          "start_offset" : 1791,
          "end_offset" : 1796
        } ]
      },
      "11 30 p.m" : {
        "doc_freq" : 1,
        "ttf" : 1,
        "term_freq" : 1,
        "tokens" : [ {
          "position" : 306,
          "start_offset" : 1791,
          "end_offset" : 1800
        } ]
      }
    }
  }
}

I convert it to a string and pass it to Play's JSON Parser

val termVec = json_reader.string()
val json = Json.parse(termVec)

Since I am using play 2.3.8, so I referred this documentation. As per the documentation, in order to traverse a JsValue structure. But parse converts to JsonNode type. None of the examples given in the documentation are working.

So doing val indexName = json \ "_index" results in error

Error:(82, 26) value \ is not a member of com.fasterxml.jackson.databind.JsonNode
    val indexName = json \ "_index"
                         ^

How should I use play so that able to get key-value pairs?

2

There are 2 best solutions below

0
On BEST ANSWER

Play has APIs for both Java and Scala. You're using the Java api.

You want to use (Scala): import play.api.libs.json._

And not (Java): import play.libs._

Try this:

val json: JsValue = play.api.libs.json.Json.parse(termVec)
val indexName = json \ "_index"
0
On

Check the import makes sure that you have this:

import play.api.libs.json.JsValue