Friday, 17 May 2019

Reading JSON data using Scala


JSON
JSON stands for JavaScript Object Notation. JSON is a lightweight format for storing and transporting data. JSON is often used when data is sent from a server to a web page. JSON is "self-describing" and easy to understand.
Here, we will discuss how Scala is reading JSON data. Steps, which I follows are as follow :
Step 1 : Open online Json editor and paste it in editor for data validation.
Example :
-------------Json Data ------------
{
      "name" : "Watership Down",
      "location" : {
      "lat" : 51.235685,
      "long" : -1.309197
      },
      "residents" : [ {
      "name" : "Fiver",
      "age" : 4,
      "role" : null
    }, {
      "name" : "Bigwig",
      "age" : 6,
      "role" : "Owsla"
    } ]
  }
After pasting data into online json editor you will see result in below format : 

 Fig: Online JSON Editor
Step 2 :
Open Intellij IDE Fileà New Project à Enter Project Name à Select Scala and sbt and click on Ok button.
Step 3 :
Open built.sbt file and include below library by adding below lines
libraryDependencies += "com.typesafe.play" %% "play-json" % "2.7.2"
//for performing json operation by using import play.api.libs.json._

 Fig: built.sbt of project
Step 4:
Included one new package named as "Json_Operation", Once package got included,need to create "Json_Oper" Scala object file and paste below code in IDE.
Example :
package Json_operation
import play.api.libs.json._
object Json_Oper {
  def main(args:Array[String]): Unit =
  {
  try {
    val json: JsValue = Json.parse(
      """
    {
      "name" : "Watership Down",
      "location" : {
      "lat" : 51.235685,
      "long" : -1.309197
      },
      "residents" : [ {
      "name" : "Fiver",
      "age" : 4,
      "role" : null
    }, {
      "name" : "Bigwig",
      "age" : 6,
      "role" : "Owsla"
    } ]
  }
  """)
    val get_name = json.\("name")
    println(get_name)
    val lat = (json.\("location").\ ("lat") )
    println(lat)
    var get_val = (json \ "name")  // here we are getting the value of key "name"
    println(get_val)
  }
    catch {
      case e=>e.printStackTrace()
    }
  }
}
//Output
JsDefined("Watership Down")
JsDefined(51.235685)
JsDefined("Watership Down")

To remove JsDefined then we have to use below code :
val get_name = json.\("name").as[JsString].value
println(get_name)
val lat = (json.\("location").\ ("lat") ).as[JsNumber].value
println(lat)
var get_val = (json \ "name").as[JsString].value  // here we are getting the value of key "name"
println(get_val)

//Output
Watership Down
51.235685
Watership Down

No comments:

Post a Comment

Use filter method to filter a Scala collection

Use filter method to filter a Scala collection To use filter on your collection, give it a predicate to filter the collection elements as...