使用 JSON 字符串中的嵌套映射
给定一个像这样的 JSON 字符串:
{"Locations":
{"list":
[
{"description": "some description", "name": "the name", "id": "dev123"},
{"description": "other description", "name": "other name", "id": "dev59"}
]
}
}
我想从解析上述字符串的函数返回“id”列表。 JSON.parseFull()
(来自 scala.util.parsing.json
)给我一个 Option[Any]
类型的结果。 Scala REPL 将其显示为 Some(Map(Locations -> Map(list -> List(Map(id -> dev123, ...
)),作为 Scala 的初学者,我很困惑 ”
Scala API 文档建议“到 将其视为集合或monad 并使用 map、flatMap、filter 或 foreach”。顶级元素是一个 Option[Any],但是应该是 Some,其中 Map 应该包含单个键“Locations”,应该包含单个键“list”最后是一个列表。在 Scala 中编写检索“id”的函数的惯用方法是什么?
Given a JSON string like this:
{"Locations":
{"list":
[
{"description": "some description", "name": "the name", "id": "dev123"},
{"description": "other description", "name": "other name", "id": "dev59"}
]
}
}
I'd like to return a list of "id"s from a function parsing the above string. JSON.parseFull()
(from scala.util.parsing.json
) gives me a result of type Option[Any]
. Scala REPL shows it as Some(Map(Locations -> Map(list -> List(Map(id -> dev123, ...
and as a beginner in Scala I'm puzzled as to which way to approach it.
Scala API docs suggest "to treat it as a collection or monad and use map, flatMap, filter, or foreach". Top-level element is an Option[Any] however that should be Some with a Map that should contain a single key "Locations", that should contain a single key "list" that finally is a List. What would be an idiomatic way in Scala to write a function retrieving the "id"s?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
首先,您应该将 json 从 Any 转换为正确的类型:
然后您可以使用
map
方法从 Option 中提取 ids:First of all, you should cast json from Any to right type:
And then you may extract ids from Option using
map
method:因为 Any 到处都是返回的结果,所以你必须进行强制转换。使用我之前的答案之一:
Because Any is everywhere is the returned result, you'll have to cast. Using one of my earlier answers:
对于此类任务,您应该查看 Rapture.io。我也是一个 Scala 初学者,但从我搜索的内容来看,这似乎有最友好的语法。这是一个简短的示例,取自 gist:
For this type of tasks, you should take a look at Rapture.io. I'm also a scala beginner, but from what I've searched for, this seems to have the friendliest syntax. Here's a short example, taken from a gist:
这是你需要的吗? (使用 lift-json)
Is this what you need? (using lift-json)
在 JSON 的 SON 分支中,这将起作用。请注意,我没有使用解析器。并不是说它不存在。只是使用构建器方法创建 JSON 对象更容易:
或者使用 a 进行理解:
In a branch of SON of JSON, this will work. Note that I'm not using the parser. Not that it doesn't exist. It's just that creating an JSON object using the builder methods is easier:
Or use a for comprehension: