0

I am trying to parse a simple json by using scala built in functions. But till now no positive result.Could you please provide any sample code or ideas to implement the below logic.

For example, I have a json input like this

val input_json = {"name" : "john", "id" : 101}

now my requirement is to parse the above json and store name and id values into two variables namely v1 & v2 by using scala built in functions.

Please provide sample code for parsing above json.

Ramesh Maharjan
  • 41,071
  • 6
  • 69
  • 97
Vasudeva
  • 9
  • 2
  • Please share what you have tried already. – Krzysztof Atłasik May 02 '18 at 13:11
  • Well, ideally you should try something like: https://github.com/json4s/json4s – Pavel May 02 '18 at 13:15
  • 1
    Please have a look at the following post https://stackoverflow.com/questions/4170949/how-to-parse-json-in-scala-using-standard-scala-classes – Chaitanya May 02 '18 at 13:32
  • Just I am trying to use scala.util.parsing.json.JSON package. But didn't get clarity how to use it. In pl/sql(Oracle,Postgres) it is pretty easy to handle JSON by using simple methods. Do we have any such kind of methods in scala – Vasudeva May 03 '18 at 08:22

1 Answers1

0

you can use scala.util.parsing.json.JSON parseFull as below

val input_json = """{"name":"john","id":101}"""

import scala.util.parsing.json.JSON
val (v1, v2) = JSON.parseFull(input_json).collect{case map: Map[String, Any] => (map("name"), map("id"))}.get

//v1: Any = john
//v2: Any = 101.0

You can cast them later on

Ramesh Maharjan
  • 41,071
  • 6
  • 69
  • 97