JSON.jl output undecorated/unquoted string

Hi,

I have a singleton type Undefined which is meant to match JavaScript’s undefined primitive. As such, when JSON rendered, this should output as undefined instead of the default "undefined" (not wrapped in double quotes, similar to how Nothing renders as null or Bool as true or false).

Specializing JSON.lower seems to do the trick partially, but I don’t know what to output in the specialization so that the output is not wrapped in quotes.

For example, this results in null because Base.print returns nothing. How can I return the undecorated/unquoted string or how can this be done?

JSON.lower(::Undefined) = Base.print("undefined")

Thank you

undefined is not valid in JSON so you probably need to come up with some other way of serializing/deserializing it (maybe a dict with a sentinel key).

2 Likes

Thanks, yes, valid point.

More correctly phrased, I’m generating a JS configuration object based on Julia data (so generating JS code) using JSON.jl. And I need to customize how some of the Julia objects are JSON serialized as the JS library expects a proper JS undefined value.

After more trial and error I seem to have nailed it. Leaving it here for posterity:

JSON.show_json(io::JSON.Writer.StructuralContext, context::JSON.Serializations.CommonSerialization, x::Undefined) = Base.print(io, "undefined")