Home > other >  Obtaining the value from any key-value from a string representation of a json in Scala (using scala.
Obtaining the value from any key-value from a string representation of a json in Scala (using scala.

Time:09-17

Imagine I have a json (in string format) that looked like:

val jsonString: String = "
    {
      "toys": {
        "orange toys": {
           "brand":"Toys-R-Us",
           "price":"123.45"
         } 
      },
      "date":"05-27-1996" 
    }
"

My question is, how can I get the value for "brand" (Toys-R-Us), in Scala, using the scala.util.parsing.json library? I am assuming that this might require the traversing of the json or maybe even easier, a way to look up the key "brand" and from their obtaining the value.

CodePudding user response:

The scala.util.parsing.json library is outdated, unsafe for open systems, and not included in the latest version of the Scala library.

Use dijon FTW!

import dijon._
import scala.language.dynamics._

val jsonString: String = """
    {
      "toys": {
        "orange toys": {
           "brand":"Toys-R-Us",
           "price":"123.45"
         } 
      },
      "date":"05-27-1996" 
    }
"""

println(parse(jsonString).toys.`orange toys`.brand)

Here is a runnable code on Scastie that works fine with Scala 2 and Scala 3.

  • Related