'Find the maximum value from JSON data in Scala

I am very new to programming in Scala. I am writing a test program to get maximum value from JSON data. I have following code:

import scala.io.Source
import scala.util.parsing.json._

object jsonParsing{

//Id int `json:"id"`
//Price int `json:"price"`

def main(args: Array[String]): Unit = {

    val file_name = "jsonData.txt"

    val json_string = scala.io.Source.fromFile("jsonData.txt").getLines.mkString

    val json_arr = json_string.split(",")

    json_arr.foreach {println}  

    }
}

The json_arr.foreach {println} prints following data:

[{ "id":1
"price":4629}
 { "id":2
"price":7126}
 { "id":3
"price":8862}
 { "id":4
"price":8999}
 { "id":5
"price":1095}]

I am stuck at the part of figuring out how to find the maximum price from such JSON data? That is, in this case the output should be '8999'.



Solution 1:[1]

you can try something like this below:

    package com.x.x.integration.commons

import collection.immutable.IndexedSeq
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser

case class wrapperObject(val json_string: Array[MyJsonObject])
case class MyJsonObject(val id:Int ,val price:Int)

object Demo {

    val gson = new Gson()
    def main(args: Array[String])={
        val json_string = scala.io.Source.fromFile("jsonData.txt").getLines.mkString
        //val json_string= """{"json_string":[{"id":1,"price":4629},{"id":2,"price":7126},{"id":3,"price":8862},{"id":4,"price":8999},{"id":5,"price":1095}]}"""
        val jsonStringAsObject= new JsonParser().parse(json_string).getAsJsonObject
        val objectThatYouCanPlayWith:wrapperObject = gson.fromJson(jsonStringAsObject, classOf[wrapperObject])
        var maxPrice:Int = 0
        for(i <- objectThatYouCanPlayWith.json_string if i.price>maxPrice) 
        {
            maxPrice=  i.price
        }
        println(maxPrice)
    }
}

check if it helps you

Solution 2:[2]

I also recommend to use Json4s or playJson.

But you could do without any libraries as such.

val json = """[{"id":1,"price":100},{"id":2, "price": 200}]"""
val priceRegex = """"price"\s*:\s*(\d+)""".r

val maxPrice = priceRegex.findAllIn(json).map({
  case priceRegex(price) => price.toInt
}).max
println(maxPrice) // print 200

Solution 3:[3]

Although Play JSON is handy, you could use Regex as well.

import scala.io.Source
import scala.util.matching.Regex._

val jsonString = Source
    .fromFile("jsonData.txt")
    .getLines.mkString.split(",")

var maxPrice = 0
jsonString.foreach(each => {
   val price: Option[Match] = ("\"price\":(\\d+)").r.findFirstMatchIn(each)
   if (price.isDefined) {
      maxPrice = Math.max(maxPrice, price.get.group(1).toInt)
   }
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 takezoux2
Solution 3 NaHeon