我有以下Json:

{
  "web-category" : "macaroons",
  "sub-categories" : [
     { "name" : "pink" },
     { "name" : "blue" },
     { "name" : "green" }
  ]

}

I have got it in Play as a JsObject. So I can now successfully do the following:

//(o is the JsObject)

val webCat:Option[String] = (o \ "web-category").asOpt[String]

println(webCat.toString)

>> Some(macaroons)

到目前为止,一切顺利.但是如何访问数组Json对象呢?我有这个...

val subCats:Option[JsArray] = (o \ "sub-categories").asOpt[JsArray]

println(subCats.toString)

>> Some([{"name" : "blue"},{"name" : "green"},{"name" : "pink"}])

but what I need is to take the JsArray and get a List of all the names something like this:

List("blue", "green", "pink")

不知道如何访问JsArray.

谢谢你在这方面的帮助.

推荐答案

I'd argue that it's generally a good idea to move from JSON-land to native-Scala-representation-land as early as possible. If obj is your JsObject, for example, you can write this:

val subCategories = (obj \ "sub-categories").as[List[Map[String, String]]]

val names = subCategories.map(_("name"))

Or even:

case class Category(name: String, subs: List[String])

import play.api.libs.functional.syntax._

implicit val categoryReader = (
  (__ \ "web-category").read[String] and
  (__ \ "sub-categories").read[List[Map[String, String]]].map(_.map(_("name")))
)(Category)

And then:

obj.as[Category]

后一种方法使错误处理更加清晰(例如,在这个顶层,您可以用asOpt替换as),并且如果您有JsArray个这样的对象,那么它可以与其他Reads类型的类实例很好地组合,例如,您只需编写array.as[List[Category]]个,就可以得到预期的结果.

Json相关问答推荐

使用JSONata将具有相同键的字典合并

如何使用JQ打印每个根级对象键一行?

使用动态和可变JSON的图表多条

JOLT转换以根据条件删除json对象

当 JSON 字段名称有空格时,ABAP 中的 JSON 反序列化

使用 jolt 变换压平具有公共列 JSON 的复杂嵌套

Jolt 转换数组对象并将某些字段移动到嵌套数组

为什么根据其他工具,来自 aws rds 的 JSON 在 Docker 中格式错误运行?

JOLT 转换 - 删除 JSON 数组中的空 node

Rails 控制器无需编码即可渲染 json

如何删除 django jsonfield 中的特定项目

按 JSON 数据类型 postgres 排序

谷歌浏览器不允许我放置断点

android - 在 adb logcat 输出中格式化 json 字符串

字符串的 Gson 数组到 JsonArray

如何将 Swift 对象转换为字典

as_json 没有在关联上调用 as_json

字符串格式 JSON 字符串给出 KeyError

Python 到 JSON 序列化在十进制上失败

雅虎财经全币种报价 API 文档