chiappone
chiappone

Reputation: 2908

Try to convert json4s values into integers

I have random JSON strings that contain string values when they are really numbers but I have no way to know what fields they might be when coming into my system.

For example:

{
   "some_key":"1234",
   "another_key":{
      "sub_key":"4243",
      "a_string":"this is a valid string and should not be converted"
   }
}

Does any one know of a simple way to try to convert json values into integers using json4s?

Upvotes: 1

Views: 1367

Answers (2)

chiappone
chiappone

Reputation: 2908

Figured it out. This piece of code does just what I need:

private def convertNumbers(json: JValue) =
  json.transformField {
    case JField(k, v) ⇒ k → (v match {
      case s: JString ⇒ Try(JInt(s.s.toInt)).getOrElse(s)
      case o          ⇒ o
    })
  }

Upvotes: 2

Will Fitzgerald
Will Fitzgerald

Reputation: 1382

Unfortunately, because these keys are encoded as strings, you'll need to convert them. So, you could do something like this:

val json = parse("""{some_key":"1234"}""")
Try((json \ "some_key").values.toString.toInt) match {
  case Success(i) => JInt(i)
  case Failure(i) => s
}

This will return a JInt if it can convert to an Int, or JString otherwise

Upvotes: 1

Related Questions