1

I have a Json string, after parsing I want it to remain in decimal form.

import play.api.libs.json._

val jsonString = """{"value":2.0}"""

println(jsonString)
println(Json.parse(jsonString))

The output of the code above is:

{"value":2.0}
{"value":2}

I need it to be

{"value":2.0}
{"value":2.0}
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
codeMouse
  • 31
  • 3

2 Answers2

2

play-json created an option to preserve zero decimals

https://github.com/playframework/play-json/pull/831/files

Just add -Dplay.json.serializer.preserveZeroDecimal=true to VM options.

codeMouse
  • 31
  • 3
1

When you say Json.parse(jsonString) you get a JsValue representing both the key "value" and the value "2.0". To get at the 2 you need to lookup the "value" key from the result:

scala> Json.parse(jsonString) \ "value"
res4: play.api.libs.json.JsLookupResult = JsDefined(2)

Currently the 2 is still represented in the Json library. To extract it to a native scala format you can use the as function on a play JsValue:

# For a whole number
scala> (Json.parse(jsonString) \ "value").as[Int]
res8: Int = 2

# For a decimal, like you want!!
scala> (Json.parse(jsonString) \ "value").as[Double]
res10: Double = 2.0

It should be noted that a number of types are difficult to represent in JSON such as decimals, dates, binary srings and regexs. If 2 and 2.0 is significant to you it may be worth reaching out and discussing with the person who generates the JSON in the first place. It may be that you need the number wrapped in quotes (to be treated like a string instead of a JsNumber).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number

Philluminati
  • 2,649
  • 2
  • 25
  • 32
  • With my case I was able to solve it using a system property from play-json but I really appreciate your input, I can definitely use these learnings in a different use case. Thanks! – codeMouse Mar 29 '23 at 13:58