在Scala中创建多维数组 [英] Creating a multidimensional array in scala
问题描述
我正在解析这样的json对象:
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)
但是它不起作用.如何在for循环中创建多维数组?
But it doesn't work. How can I create a multidimensional array in the for loop?
希望我能澄清一下:
在PHP中将是这样:
product_array2[id][propName]=propValue;
推荐答案
如果要访问该结构,@ lpaul7的答案将告诉您如何操作.如果要更新结构,则需要处理嵌套的不可变Map,或者将结果确实转换为可变结构(尝试对Array进行处理).
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).
这有点令人讨厌:
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]]
}
查询:
im("id")("age")
不变的更新:
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)
可变更新:
mut("id")("age") = 55
换句话说,您将真正想要一个无噪声的Scala JSON解决方案,例如 Lift的json , sjson 或
In other words, you will really want a noise-free Scala JSON solution, such as the Lift's json, sjson, or Jerkson libraries.
这篇关于在Scala中创建多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!