`toString` on Json objects

26 views
Skip to first unread message

Jon Pretty

unread,
Feb 16, 2015, 8:58:02 AM2/16/15
to raptur...@googlegroups.com
Dear all,

I've got a design question, raised by my last response. Currently, if you call `toString` on a `Json` object, it will produce some perfectly valid-looking JSON output, *unless* it happens to be an illegal value, for example:

val bad = json"""{ "foo": "bar" }""".quux

The value `quux` doesn't exist, so `toString` returns `undefined` instead.

But there's never an exception thrown, which means that your application could be printing out invalid JSON (i.e. the word "undefined") without you being immediately aware of it.

The solution is that you should be using the `Json.format(json)` method instead, but you could be forgiven for being unaware of it, and considering `toString` to be sufficient.

I'd like to propose a change to the `toString` method such that rather than outputting ready-to-use JSON, it outputs a Scala representation of that JSON, such that users would be discouraged from using `toString`. Here's what it would look like:

scala> val js = Json(Map("foo" -> "bar"))
js: rapture.json.Json = json"""{"foo":"bar"}"""

or in the event of a failure,

​scala> val js = Json(Map("foo" -> "bar")).quux
js: rapture.json.Json = undefined

This would conveniently make the output copy/pastable back into Scala, but it would break code for anyone relying on `toString` for output.

Thoughts, or +1s, anyone?

Cheers,
Jon


--
Jon Pretty | @propensive

Simon Vos

unread,
Mar 20, 2015, 4:05:11 PM3/20/15
to raptur...@googlegroups.com
This and adding an example to the EXAMPLES.md of using Json.Format would be a good idea.

Op maandag 16 februari 2015 14:58:02 UTC+1 schreef Jon Pretty:

Jon Pretty

unread,
Mar 22, 2015, 1:34:48 PM3/22/15
to raptur...@googlegroups.com
Thanks, Simon.

I'll make sure I do both at the same time!

Cheers,
Jon

--
You received this message because you are subscribed to the Google Groups "Rapture users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rapture-user...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages