Controlling JSON serialization for JSON booleans

I am struggling to output true and false as JSON booleans.

json_write(user_output, _{some_boolean: true}) produces {"some_boolean":"true"} but the other end expects {"some_boolean":true}

I looked at json_write_hook/4 but there were no examples. I had hoped asserta((json_write_hook(my_alias_for_true, Stream, _, _) :- write(Stream, true))). would work, but it did not.

You can use the hook, but it must be defined in the module json, as follows (not tested).

:- multifile json:json_write_hook/4.

json:json_write_hook(my_true, Stream, _, _) :- 
    write(Stream, true).

However, you can also use json_write/3 and the option true(my_true). The default is a term @(true). When using json_write_dict/2,3, the default is to use Prolog strings for string values and the atoms true, false and null work as expected. But then, strings are not always that practical for values :frowning:

Ideally we should have some kind of schema-like annotation that tells us which values should be handled as strings and which as atoms. Just using JSON Schema will do for the Booleans, but won’t do with the general case where some JSON string values are “identifier” like and we want to handle as atoms in Prolog and others are more “natural language” like and we want to handle as strings in Prolog.

1 Like