user1435853
user1435853

Reputation: 653

Scala looping through an object

I am getting an object through this line:

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

The object when printed out looks like this:

(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)) 

how do I loop through the array/object to extract the keys and values?

Update:

When I try to loop through the object it send blank values to key and value, below:

for((key, value) <- product_array)     {       

}

Here is the original 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"
   }
}

Upvotes: 2

Views: 4666

Answers (2)

lambdas
lambdas

Reputation: 4080

First, note that parseFull returns Option, it means your first step is to check if it contains something or not (parsing error occured for example), I suggest you to use pattern matching for this:

products match {
  case Some(p) => println("Products found")
  case None => println("Error parsing JSON")
}

If your option contains actual value, it'll be placed in p variable. Next, note that parseFull returned Option[Any], so p is Any too. It should be casted before iterating:

p.asInstanceOf[Map[String,Map[String,Any]]]

Now you can iterate through the map, let's use for:

for {
  (id, desc) <- p.asInstanceOf[Map[String,Map[String,Any]]]
  (propName, propValue) <- desc
} println(propName + "=" + propValue)

It looks like a single loop, but actually it is a double loop. It iterates through the outer map, and enters each inner map. Inside the loop body you can access id, desc, propName and propValue variables. It is probably what you are looking for.

Entire script:

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")
}

Good luck.

Upvotes: 5

Larsenal
Larsenal

Reputation: 51156

So you have a nested Map. Try something like this:

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
    }
}

Upvotes: 2

Related Questions