Teodorico Levoff Teodorico Levoff - 6 months ago 41
JSON Question

Parse JSON data into Scala List and HashMap

I have JSON data shown below. I am using Python to encode a list, a dictionary and another list into JSON. The final JSON data will look like so:

{
"0": [3, 3, 3],
"1": {
"0": [0, 8, 9],
"1": [1, 2, 3, 4, 10, 11],
"2": [4]
},
"2": [1, 1, 1, 1]
}
.
My aim is to write some type of Scala function to extract the JSON data in a way that allows
"0": [3, 3, 3]
to be a
List(3,3,3)
,
{"0":[0,8,9], ...}
to be a
HashMap[Int,List[Int]]
and
"2": [1, 1, 1, 1]
to be a
List(1,1,1,1)
. Note the length of original Python list and dictionary will vary in size, and the
"0", "1" and "2"
will always be there representing the list, dictionary and list in this order. I am quite new to Scala and struggling on how to do it without using external libraries. I am trying to use spray-json to do it, since I am using a newer version of Scala(no built-in json parser).

Ren Ren
Answer

That doesn't look like valid JSON to me, which means any of the JSON parsers you could use won't work. Is that structure fixed? You may want to instead convert it to something thats valid JSON.

eg.

{
  "list" : [ 1,1,1],
   "someotherObject" : {
         "0" : [1,2,3]
   },
   "anotherList" : [9,8,7]
}

Then you could use Argonaut (for example), and define a decoder, which tells how to map that JSON to object types you specify. See http://argonaut.io/doc/codec/