JSON parsing removes decimal trailing zeros

508 Views Asked by At

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}
2

There are 2 best solutions below

0
codeMouse On BEST ANSWER

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.

1
Philluminati On

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