我通过这一行获得了一个对象:
val product_array:Option[Any] = scala.util.parsing.json.JSON.parseFull(products_json)
打印出来的对象如下所示:
(product1Id,Map(product_picture -> https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/IPhone_3G.png/250px-IPhone_3G.png, product_price -> 299.99, recipient_picture -> https://www.allianz.com/static-resources/de/presse/mediendatenbank/people/v_1338807733000/zimerer_portrait_small_326x217.jpg, product_amount_gifted -> 100.00, recipient_username -> jDoe, product_name -> iPhone 3G, recipient_id -> 12345))(product2Id,Map(product_picture -> https://upload.wikimedia.org/wikipedia/en/thumb/7/7c/1stGen-iPad-HomeScreen.jpg/220px-1stGen-iPad-HomeScreen.jpg, product_price -> 399.99, recipient_picture -> https://image1.masterfile.com/em_w/05/11/94/400-05119409w.jpg, product_amount_gifted -> 200.00, recipient_username -> MJohnson, product_name -> iPad, recipient_id -> 67890))
如何循环遍历数组/对象以提取键和值?
更新
当我尝试遍历对象时,它会将空白值发送到键和值,如下所示:
for((key, value) <- product_array) {
}
这是原始的json:
{
"product1Id":{
"product_name":"iPhone 3G",
"product_price":"299.99",
"product_amount_gifted":"100.00",
"product_picture":"https:\/\/upload.wikimedia.org\/wikipedia\/commons\/thumb\/7\/73\/IPhone_3G.png\/250px-IPhone_3G.png",
"recipient_picture":"https:\/\/www.allianz.com\/static-resources\/de\/presse\/mediendatenbank\/people\/v_1338807733000\/zimerer_portrait_small_326x217.jpg",
"recipient_username":"jDoe",
"recipient_id":"12345"
},
"product2Id":{
"product_name":"iPad",
"product_price":"399.99",
"product_amount_gifted":"200.00",
"product_picture":"https:\/\/upload.wikimedia.org\/wikipedia\/en\/thumb\/7\/7c\/1stGen-iPad-HomeScreen.jpg\/220px-1stGen-iPad-HomeScreen.jpg",
"recipient_picture":"https:\/\/image1.masterfile.com\/em_w\/05\/11\/94\/400-05119409w.jpg",
"recipient_username":"MJohnson",
"recipient_id":"67890"
}
}
答案 0 :(得分:5)
首先,请注意parseFull
返回Option
,这意味着您的第一步是检查它是否包含某些内容(例如,发生了解析错误),我建议您使用模式匹配:
products match {
case Some(p) => println("Products found")
case None => println("Error parsing JSON")
}
如果您的选项包含实际值,则会将其放在p
变量中。接下来,请注意parseFull返回Option[Any]
,因此p
也是Any
。它应该在迭代之前进行转换:
p.asInstanceOf[Map[String,Map[String,Any]]]
现在您可以遍历地图,让我们使用for
:
for {
(id, desc) <- p.asInstanceOf[Map[String,Map[String,Any]]]
(propName, propValue) <- desc
} println(propName + "=" + propValue)
它看起来像一个循环,但实际上它是一个双循环。它遍历外部地图,并进入每个内部地图。在循环体内,您可以访问id
,desc
,propName
和propValue
变量。这可能就是你要找的东西。
整个脚本:
import scala.util.parsing.json.JSON._
val json = """{"product1Id":{"..."recipient_id":"67890"}}"""
val products = parseFull(json)
products match {
case Some(p) =>
for {
(id, desc) <- p.asInstanceOf[Map[String,Map[String,Any]]]
(propName, propValue) <- desc
} println(propName + "=" + propValue)
case None => println("Error parsing JSON")
}
祝你好运。
答案 1 :(得分:2)
所以你有一个嵌套的Map。尝试这样的事情:
val your_map = product_array.get().asInstanceOf[Map[String,Map[String,Any]]]
for((key1, value1) <- your_map){
for((key2, value2) <- value1){
// now use key2 and value2
}
}