user1491739
user1491739

Reputation: 1017

Creating a multidimensional array in scala

I am parsing a json object like this:

val product_array:Option[Any] = scala.util.parsing.json.JSON.parseFull(products_json)

var product_array2 = Array()

product_array match {
case Some(p) => {
for {
  (id, desc) <- p.asInstanceOf[Map[String,Map[String,Any]]]
  (propName, propValue) <- desc
}  product_array2(id) ++ Array(propName->propValue.toString)
}
case None => test = "No products in shopping cart"
}

The problem is that I am trying to create a multidimensional array with this line:

product_array2(id) ++ Array(propName->propValue.toString)

But it doesn't work. How can I create a multidimensional array in the for loop?

Hopefully I can clarify:

In PHP it would be this:

product_array2[id][propName]=propValue;

Upvotes: 2

Views: 611

Answers (2)

0__
0__

Reputation: 67280

If you want to access the structure, the answer of @lpaul7 will tell you how. If you want to update the structure, you either need to deal with the nested immutable Map, or convert the result indeed into a mutable structure (what you tried to do with the Array).

This gets all a bit nasty:

import scala.util.parsing.json.JSON._

val json = """{"id": {"age": 33}}"""

val im = parseFull(json) match {
  case Some(m: Map[_, _]) => 
    m.asInstanceOf[Map[String, Any]].collect {
      case (key, value: Map[_, _]) => (key, value.asInstanceOf[Map[String, Any]])
    }
  case _ => Map.empty[String, Map[String, Any]]
}

Query:

im("id")("age")

Immutable update:

val updated = im + ("id" -> (im.getOrElse("id", Map.empty) + ("age" -> 44)))

Mutable structure (using mutable maps both for the outer and inner structure):

import collection.{breakOut, mutable}

val mut: mutable.Map[String, mutable.Map[String, Any]] = 
   im.map { case (key, inner) => key -> mutable.Map(inner.toSeq: _*)} (breakOut)

Mutable update:

mut("id")("age") = 55

In other words, you will really want a noise-free Scala JSON solution, such as the Lift's json, sjson, or Jerkson libraries.

Upvotes: 2

lambdas
lambdas

Reputation: 4080

You can achieve it easily:

import scala.util.parsing.json.JSON._

val products_json = """{"p...67890"}}"""

val product_array = 
  parseFull(products_json).get.asInstanceOf[Map[String,Map[String,Any]]]

println(product_array("product1Id")("product_name"))

Upvotes: 1

Related Questions