[英]Converting a JSON object to a value list of a particular key in scala (play)
I have a Json object, which is an output of Json.parse, which is of format 我有一个Json对象,它是Json.parse的输出,其格式是
{ "main_data" : [ {"a" : 1, "b" :2} , {"a" : 3, "b" : 4}, {"a" : 5, "b" : 6}]}. {“ main_data”:[{“ a”:1,“ b”:2},{“ a”:3,“ b”:4},{“ a”:5,“ b”:6}]}。
I want to create a list out of this Json object with the values of all the "a" key. 我想用所有“ a”键的值从该Json对象创建一个列表。 So in the above example it will be [1,3,5]. 因此,在上面的示例中,它将为[1,3,5]。 As I am new to functional programming the first thing came to my mind was to write a For loop and traverse through the Json object to get the list. 当我刚接触函数式编程时,我想到的第一件事是编写一个For循环并遍历Json对象以获取列表。
But I was wondering is there a Functional/Scala way to do the above, using Map or flatMap ? 但是我想知道是否有使用Map或flatMap的Functional / Scala方法来完成上述操作?
import play.api.libs.json._
val parsed = Json.parse("""{"main_data":[{"a":1,"b":2},{"a":3,"b":4},{"a":5,"b":6}]}""")
val keys = parsed \\ "a"
val result = keys.flatMap(_.asOpt[Int]) // List(1, 3, 5)
You can use something like this 你可以用这样的东西
val json = Json.parse(yourJsonString)
val aKeys = json \\ "a"
// aKeys: Seq[play.api.libs.json.JsValue] = List(1, 3, 5)
// If you need integers instead of JsValues, just use map
val integersList = aKeys.map(x => x.as[Int])
There are plenty of choices. 有很多选择。 Let's say you have: 假设您有:
import play.api.libs.json._
val txt =
"""
|{ "main_data" : [ {"a" : 1, "b" :2} , {"a" : 3, "b" : 4}, {"a" : 5, "b" : 6}]}
""".stripMargin
val json = Json.parse(txt)
First approach if you are interested only in a
: 如果您只对感兴趣,则a
:
(json \ "main_data")
.as[List[Map[String, Int]]]
.flatten
.foldLeft(List[Int]()){
case (acc, ("a", i)) => acc :+ i
case (acc, _) => acc
}
The second more general: 第二个更一般:
(json \ "main_data")
.as[List[Map[String, Int]]]
.flatten
.groupBy(_._1)
.map {
case (k, list) => k -> list.map(_._2)
}
.get("a")
And the result is: 结果是:
res0: Option[List[Int]] = Some(List(1, 3, 5))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.