Scala 将字符串转换为映射
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19938449/
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
Scala Convert a string into a map
提问by Learner
What is the fastest way to convert this
转换这个的最快方法是什么
{"a":"ab","b":"cd","c":"cd","d":"de","e":"ef","f":"fg"}
{"a":"ab","b":"cd","c":"cd","d":"de","e":"ef","f":"fg"}
into mutable map in scala ? I read this input string from ~500MB file. That is the reason I'm concerned about speed.
进入scala中的可变地图?我从 ~500MB 文件中读取了这个输入字符串。这就是我关心速度的原因。
采纳答案by sventechie
That looks like a JSON file, as Andrey says. You should consider this answer. It gives some example Scala code. Also, this answer gives some different JSON libraries and their relative merits.
正如安德烈所说,这看起来像一个 JSON 文件。你应该考虑这个答案。它给出了一些示例 Scala 代码。此外,这个答案给出了一些不同的 JSON 库及其相对优点。
回答by Yann Moisan
If your JSON is as simple as in your example, i.e. a sequence of key/value pairs, where each value is a string. You can do in plain Scala :
如果您的 JSON 与您的示例一样简单,即一系列键/值对,其中每个值都是一个字符串。您可以在普通 Scala 中执行以下操作:
myString.substring(1, myString.length - 1)
.split(",")
.map(_.split(":"))
.map { case Array(k, v) => (k.substring(1, k.length-1), v.substring(1, v.length-1))}
.toMap
回答by Andrey Chaschev
The fastest way to read tree data structures in XML or JSON is by applying streaming API: Hymanson Streaming API To Read And Write JSON.
在 XML 或 JSON 中读取树数据结构的最快方法是应用流 API:Hymanson Streaming API To Read And Write JSON。
Streaming would split your input into tokens like 'beginning of an object' or 'beginning of an array' and you would need to build a parser for these token, which in some cases is not a trivial task.
流式传输会将您的输入拆分为诸如“对象的开始”或“数组的开始”之类的标记,并且您需要为这些标记构建解析器,这在某些情况下并不是一项微不足道的任务。

