3

I am new in Scala and I want to extract some values from json

I have a big json data as a string and I want to extract only review_score value, I am using import scala.util.parsing.json.JSON library.

var values = JSON.parseFull(bigJson)

My problem is, after parsing to json, How I get the reviewDetails Map?

a screen shot of received values

Alaeddine
  • 1,571
  • 2
  • 22
  • 46
  • Personally I've only used the jackson library, where extracting from a case class would enable you to access reviewDetails by => values.reviewDetails - I'm assuming this isn't the case here? – Gillespie Sep 22 '15 at 12:45

1 Answers1

14

parseFull will return an Option[Any] which contains either a List[Any] if the JSON string specifies an array, or a Map[String,Any] if the JSON string specifies an object, as the documentation states.

In your case, the value you want to retrieve is a key-value pair in a map which is itself a key-value pair of the global map.

It is a bit ugly, but since you know the structure of your JSON, a combination of get with asInstanceOf, will permit you to get the typed value you want.

val jsonObject = JSON.parseFull("...")
val globalMap = x.get.asInstanceOf[Map[String, Any]]
val reviewMap = globalMap.get("reviewDetails").get.asInstanceOf[Map[String, Any]]
val reviewScore = reviewMap.get("review_score").get.asInstanceOf[Double]

Note that here I use get "safely" because the value is known to exist in your context, but you can also use isEmpty and getOrElse.

If you want a scalable code, you can effectively look at How to parse JSON in Scala using standard Scala classes?

Community
  • 1
  • 1
Alexis C.
  • 91,686
  • 21
  • 171
  • 177