6

What is the fastest way to convert this

{"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.

Yann Moisan
8,3099 gold badges53 silver badges92 bronze badges
asked Nov 12, 2013 at 19:44

4 Answers 4

15

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 :

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
answered Nov 12, 2013 at 23:21

1 Comment

What if there's comma in the map value?
2

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.

answered Nov 12, 2013 at 19:56

Comments

2

The fastest way to read tree data structures in XML or JSON is by applying streaming API: Jackson 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.

answered Nov 12, 2013 at 19:53

Comments

-1

Keeping it simple. If reading a json string from file and converting to scala map

import spray.json._
import DefaultJsonProtocol._
val jsonStr = Source.fromFile(jsonFilePath).mkString
val jsonDoc=jsonStr.parseJson
val map_doc=jsonDoc.convertTo[Map[String, JsValue]]
// Get a Map key value
val key_value=map_doc.get("key").get.convertTo[String]
// If nested json, re-map it.
val key_map=map_doc.get("nested_key").get.convertTo[Map[String, JsValue]]
println("Nested Value " + key_map.get("key").get)
answered Jun 30, 2020 at 9:48

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.