在 Scala scala.util.parsing.json.JSON 中获取 Json 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32716609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 07:37:56  来源:igfitidea点击:

get Json Values in Scala scala.util.parsing.json.JSON

javajsonscalaloopsdictionary

提问by Alaeddine

I am new in Scalaand I want to extract some values from json

我是Scala 的新手,我想从json 中提取一些值

I have a big json data as a string and I want to extract only review_scorevalue, I am using import scala.util.parsing.json.JSONlibrary.

我有一个很大的 json 数据作为字符串,我只想提取review_score值,我正在使用import scala.util.parsing.json.JSON库。

var values = JSON.parseFull(bigJson)

var values = JSON.parseFull(bigJson)

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

我的问题是,解析为 json 后,我如何获得reviewDetails地图?

a screen shot of received values

接收值的屏幕截图

回答by Alexis C.

parseFullwill 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.

parseFull如文档Option[Any]所述,List[Any]如果 JSON 字符串指定一个数组,则将返回包含 a ,或者Map[String,Any]如果 JSON 字符串指定一个对象,则返回包含 a 。

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 getwith asInstanceOf, will permit you to get the typed value you want.

这有点难看,但是由于您知道 JSON 的结构,因此与 组合get使用asInstanceOf将允许您获得所需的类型值。

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 isEmptyand getOrElse.

请注意,这里我使用get“安全”,因为该值已知存在于您的上下文中,但您也可以使用isEmptygetOrElse

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

如果你想要一个可扩展的代码,你可以有效地查看如何使用标准 Scala 类在 Scala 中解析 JSON?