4

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

1
  • 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? Commented Sep 22, 2015 at 12:45

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but I get java.util.NoSuchElementException: None.get error at line 3 where reviewMap
@Alaeddine Sorry, it should have been globalMap.get("reviewDetails") instead of "review_details".
What is x (the invoking object to get)? Is it supposed to be jsonObject?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.