Vincent Claes
Vincent Claes

Reputation: 4788

parse json object where keys start with a number using scala

I want to parse the following JSON object using Scala:

val result = """{"24h_volume_usd": "9097260000.0"}"""

normally I use:

import net.liftweb.json._
case class VolumeUSDClass(24h_volume_usd:String) //<- problem 24h_volume_usd does not work
val element = parse(result)
element.extract[CryptoDataClass]

The problem is that I cannot define a case class with an argument that starts with a number. what is the best way to circumvent this?

Upvotes: 1

Views: 214

Answers (1)

Andrey Tyukin
Andrey Tyukin

Reputation: 44967

You can simply enclose the name of the variable into backticks:

implicit val formats = net.liftweb.json.DefaultFormats
val result = """{"24h_volume_usd": "9097260000.0"}"""
import net.liftweb.json._
case class VolumeUSDClass(`24h_volume_usd`:String)
val element = parse(result)
val vusdcl = element.extract[VolumeUSDClass]
println(vusdcl)

Recall that almost everything can be transformed into a valid Scala identifier if you enclose it in backticks. Even strange stuff like

val `]strange...O_o...stuff[` = 42
println(`]strange...O_o...stuff[`)

works.

The example is tested with "net.liftweb" %% "lift-json" % "3.2.0" and Scala 2.11.

Upvotes: 1

Related Questions