View source with raw comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        jan@swi-prolog.org
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2007-2026, University of Amsterdam
    7                              VU University Amsterdam
    8                              CWI, Amsterdam
    9                              SWI-Prolog Solutions b.v.
   10    All rights reserved.
   11
   12    Redistribution and use in source and binary forms, with or without
   13    modification, are permitted provided that the following conditions
   14    are met:
   15
   16    1. Redistributions of source code must retain the above copyright
   17       notice, this list of conditions and the following disclaimer.
   18
   19    2. Redistributions in binary form must reproduce the above copyright
   20       notice, this list of conditions and the following disclaimer in
   21       the documentation and/or other materials provided with the
   22       distribution.
   23
   24    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   25    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   26    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   27    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   28    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   29    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   30    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   31    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   32    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   33    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   34    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   35    POSSIBILITY OF SUCH DAMAGE.
   36*/
   37
   38:- module(json,
   39          [ json_read/2,                % +Stream, -JSONTerm
   40            json_read/3,                % +Stream, -JSONTerm, +Options
   41            atom_json_term/3,           % ?Atom, ?JSONTerm, +Options
   42            json_write/2,               % +Stream, +Term
   43            json_write/3,               % +Stream, +Term, +Options
   44            is_json_term/1,             % @Term
   45            is_json_term/2,             % @Term, +Options
   46                                        % Version 7 dict support
   47            json_read_dict/2,           % +Stream, -Dict
   48            json_read_dict/3,           % +Stream, -Dict, +Options
   49            json_write_dict/2,          % +Stream, +Dict
   50            json_write_dict/3,          % +Stream, +Dict, +Options
   51            atom_json_dict/3,           % ?Atom, ?JSONDict, +Options
   52            json/4                      % {|json(Var,...)||JSON|}
   53          ]).   54:- use_module(library(record)).   55:- use_module(library(error)).   56:- use_module(library(option)).   57:- use_module(library(lists)).   58:- use_module(library(apply)).   59:- use_module(library(quasi_quotations)).   60
   61:- use_foreign_library(foreign(json)).   62
   63:- multifile
   64    json_write_hook/4,                  % +Term, +Stream, +State, +Options
   65    json_dict_pairs/2.                  % +Dict, -Pairs
   66
   67:- predicate_options(json_read/3, 3,
   68                     [ null(ground),
   69                       true(ground),
   70                       false(ground),
   71                       end_of_file(ground),
   72                       value_string_as(oneof([atom,string])),
   73                       non_finite(oneof([error,null,json5])),
   74                       qqdict(list(compound(=(atom,var))))
   75                     ]).   76:- predicate_options(json_write/3, 3,
   77                     [ indent(nonneg),
   78                       step(positive_integer),
   79                       tab(positive_integer),
   80                       width(nonneg),
   81                       null(ground),
   82                       true(ground),
   83                       false(ground),
   84                       non_finite(oneof([error,null,json5])),
   85                       serialize_unknown(boolean)
   86                     ]).   87:- predicate_options(json_read_dict/3, 3,
   88                     [ tag(atom),
   89                       default_tag(atom),
   90                       pass_to(json_read/3, 3)
   91                     ]).   92:- predicate_options(json_write_dict/3, 3,
   93                     [ tag(atom),
   94                       pass_to(json_write/3, 3)
   95                     ]).   96:- predicate_options(is_json_term/2, 2,
   97                     [ null(ground),
   98                       true(ground),
   99                       false(ground)
  100                     ]).  101:- predicate_options(atom_json_term/3, 3,
  102                     [ as(oneof([atom,string,codes])),
  103                       pass_to(json_read/3, 3),
  104                       pass_to(json_write/3, 3)
  105                     ]).

Reading and writing JSON serialization

This module supports reading and writing JSON objects. This library supports two Prolog representations (the new representation is only supported in SWI-Prolog version 7 and later):

This module provides the json Quasi Quotation syntax that allows for embedding JSON documents in Prolog.

See also
- http_json.pl links JSON to the HTTP client and server modules.
- json_convert.pl converts JSON Prolog terms to more comfortable terms.
  131:- record json_options(
  132              null:ground = @(null),
  133              true:ground = @(true),
  134              false:ground = @(false),
  135              end_of_file:ground = error,
  136              value_string_as:oneof([atom,string]) = atom,
  137              tag:atom = '',
  138              default_tag:(var;atom) = '#',
  139              qqdict:list(compound(atom=var)),
  140              non_finite:oneof([error,null,json5]) = error).  141
  142default_json_dict_options(
  143    json_options(null, true, false, error, string, '', #, _, error)).
  144
  145
  146                 /*******************************
  147                 *       MAP TO/FROM TEXT       *
  148                 *******************************/
 atom_json_term(?Atom, ?JSONTerm, +Options) is det
Convert between textual representation and a JSON term. In write mode (JSONTerm to Atom), the option
as(Type)
defines the output type, which is one of atom (default), string, codes or chars.
  159atom_json_term(Atom, Term, Options) :-
  160    ground(Atom),
  161    !,
  162    setup_call_cleanup(
  163        open_string(Atom, In),
  164        json_read(In, Term, Options),
  165        close(In)).
  166atom_json_term(Result, Term, Options) :-
  167    select_option(as(Type), Options, Options1, atom),
  168    (   type_term(Type, Result, Out)
  169    ->  true
  170    ;   must_be(oneof([atom,string,codes,chars]), Type)
  171    ),
  172    with_output_to(Out,
  173                   json_write(current_output, Term, Options1)).
  174
  175type_term(atom,   Result, atom(Result)).
  176type_term(string, Result, string(Result)).
  177type_term(codes,  Result, codes(Result)).
  178type_term(chars,  Result, chars(Result)).
  179
  180
  181                 /*******************************
  182                 *           READING            *
  183                 *******************************/
 json_read(+Stream, -Term) is det
 json_read(+Stream, -Term, +Options) is det
Read next JSON value from Stream into a Prolog term. The canonical representation for Term is:

Here is a complete example in JSON and its corresponding Prolog term.

{ "name":"Demo term",
  "created": {
    "day":null,
    "month":"December",
    "year":2007
  },
  "confirmed":true,
  "members":[1,2,3]
}
json([ name='Demo term',
       created=json([day= @null, month='December', year=2007]),
       confirmed= @true,
       members=[1, 2, 3]
     ])

The following options are processed:

null(+NullTerm)
Term used to represent JSON null. Default @(null)
true(+TrueTerm)
Term used to represent JSON true. Default @(true)
false(+FalseTerm)
Term used to represent JSON false. Default @(false)
end_of_file(+ErrorOrTerm)
If end of file is reached after skipping white space but before any input is processed take the following action (default error):
  • If ErrorOrTerm == error, throw an unexpected end of file syntax error
  • Otherwise return ErrorOrTerm.

Returning an status term is required to process Concatenated JSON. Suggested values are @(eof) or end_of_file.

value_string_as(+Type)
Prolog type used for strings used as value. Default is atom. The alternative is string, producing a packed string object. Please note that codes or chars would produce ambiguous output and are therefore not supported.
non_finite(+How)
JSON does not support the floating point values infinity and NaN. If How is json5, accept the JSON5 tokens Infinity, -Infinity and NaN. Otherwise (default error), these are syntax errors.
See also
- json_read_dict/3 to read a JSON term using the version 7 extended data types.
  263json_read(Stream, Term) :-
  264    default_json_options(Options),
  265    (   json_value_top(Stream, Term, Options)
  266    ->  true
  267    ;   syntax_error(illegal_json, Stream)
  268    ).
  269json_read(Stream, Term, Options) :-
  270    make_json_options(Options, OptionTerm, _RestOptions),
  271    (   json_value_top(Stream, Term, OptionTerm)
  272    ->  true
  273    ;   syntax_error(illegal_json, Stream)
  274    ).
  275
  276json_value_top(Stream, Term, Options) :-
  277    stream_property(Stream, type(binary)),
  278    !,
  279    setup_call_cleanup(
  280        set_stream(Stream, encoding(utf8)),
  281        json_value_top_(Stream, Term, Options),
  282        set_stream(Stream, type(binary))).
  283json_value_top(Stream, Term, Options) :-
  284    json_value_top_(Stream, Term, Options).
  285
  286json_value_top_(Stream, Term, Options) :-
  287    get_code(Stream, C0),
  288    ws(C0, Stream, C1),
  289    (   C1 == -1
  290    ->  json_options_end_of_file(Options, Action),
  291        (   Action == error
  292        ->  syntax_error(unexpected_end_of_file, Stream)
  293        ;   Term = Action
  294        )
  295    ;   json_term_top(C1, Stream, Term, Options)
  296    ).
  297
  298json_value(Stream, Term, Next, Options) :-
  299    get_code(Stream, C0),
  300    ws(C0, Stream, C1),
  301    (   C1 == -1
  302    ->  syntax_error(unexpected_end_of_file, Stream)
  303    ;   json_term(C1, Stream, Term, Next, Options)
  304    ).
  305
  306json_term(C0, Stream, JSON, Next, Options) :-
  307    json_term_top(C0, Stream, JSON, Options),
  308    get_code(Stream, Next).
  309
  310json_term_top(0'{, Stream, json(Pairs), Options) :-
  311    !,
  312    ws(Stream, C),
  313    json_pairs(C, Stream, Pairs, Options).
  314json_term_top(0'[, Stream, Array, Options) :-
  315    !,
  316    ws(Stream, C),
  317    json_array(C, Stream, Array, Options).
  318json_term_top(0'", Stream, String, Options) :-
  319    !,
  320    get_code(Stream, C1),
  321    json_string_codes(C1, Stream, Codes),
  322    json_options_value_string_as(Options, Type),
  323    codes_to_type(Type, Codes, String).
  324json_term_top(0'-, Stream, Number, Options) :-
  325    !,
  326    (   json_options_non_finite(Options, json5),
  327        peek_code(Stream, 0'I)
  328    ->  get_code(Stream, _),
  329        must_see(`nfinity`, Stream, 'Infinity'),
  330        Number is -inf
  331    ;   json_read_number(Stream, 0'-, Number)
  332    ).
  333json_term_top(D, Stream, Number, _Options) :-
  334    between(0'0, 0'9, D),
  335    !,
  336    json_read_number(Stream, D, Number).
  337json_term_top(0'I, Stream, Number, Options) :-
  338    json_options_non_finite(Options, json5),
  339    !,
  340    must_see(`nfinity`, Stream, 'Infinity'),
  341    Number is inf.
  342json_term_top(0'N, Stream, Number, Options) :-
  343    json_options_non_finite(Options, json5),
  344    !,
  345    must_see(`aN`, Stream, 'NaN'),
  346    Number is nan.
  347json_term_top(C, Stream, Constant, Options) :-
  348    json_read_constant(C, Stream, ID),
  349    !,
  350    json_constant(ID, Constant, Options).
  351json_term_top(C, Stream, Var, Options) :-
  352    code_type(C, prolog_var_start),
  353    json_options_qqdict(Options, QQDict),
  354    nonvar(QQDict),
  355    !,
  356    json_read_var_cont(Stream, Codes),
  357    atom_codes(Name, [C | Codes]),
  358    (   memberchk(Name=Var, QQDict)
  359    ->  true
  360    ;   syntax_error(non_existing_var(Name, QQDict), Stream)
  361    ).
  362
  363json_read_var_cont(Stream, [C | L]) :-
  364    peek_code(Stream, C),
  365    code_type(C, prolog_identifier_continue),
  366    !,
  367    get_code(Stream, C),
  368    json_read_var_cont(Stream, L).
  369json_read_var_cont(_, []).
  370
  371
  372json_pairs(0'}, _, [], _) :- !.
  373json_pairs(C0, Stream, [Pair|Tail], Options) :-
  374    json_pair(C0, Stream, Pair, C, Options),
  375    ws(C, Stream, Next),
  376    (   Next == 0',
  377    ->  ws(Stream, C2),
  378        json_pairs(C2, Stream, Tail, Options)
  379    ;   Next == 0'}
  380    ->  Tail = []
  381    ;   syntax_error(illegal_object, Stream)
  382    ).
  383
  384json_pair(C0, Stream, Name=Value, Next, Options) :-
  385    json_string_as_atom(C0, Stream, Name),
  386    ws(Stream, C),
  387    C == 0':,
  388    json_value(Stream, Value, Next, Options).
  389
  390
  391json_array(0'], _, [], _) :- !.
  392json_array(C0, Stream, [Value|Tail], Options) :-
  393    json_term(C0, Stream, Value, C, Options),
  394    ws(C, Stream, Next),
  395    (   Next == 0',
  396    ->  ws(Stream, C1),
  397        json_array(C1, Stream, Tail, Options)
  398    ;   Next == 0']
  399    ->  Tail = []
  400    ;   syntax_error(illegal_array, Stream)
  401    ).
  402
  403codes_to_type(atom, Codes, Atom) :-
  404    atom_codes(Atom, Codes).
  405codes_to_type(string, Codes, Atom) :-
  406    string_codes(Atom, Codes).
  407codes_to_type(codes, Codes, Codes).
  408
  409json_string_as_atom(0'", Stream, Atom) :-
  410    get_code(Stream, C1),
  411    json_string_codes(C1, Stream, Codes),
  412    atom_codes(Atom, Codes).
  413
  414json_string_codes(0'", _, []) :- !.
  415json_string_codes(0'\\, Stream, [H|T]) :-
  416    !,
  417    get_code(Stream, C0),
  418    (   escape(C0, Stream, H)
  419    ->  true
  420    ;   syntax_error(illegal_string_escape, Stream)
  421    ),
  422    get_code(Stream, C1),
  423    json_string_codes(C1, Stream, T).
  424json_string_codes(-1, Stream, _) :-
  425    !,
  426    syntax_error(eof_in_string, Stream).
  427json_string_codes(C, Stream, [C|T]) :-
  428    get_code(Stream, C1),
  429    json_string_codes(C1, Stream, T).
  430
  431escape(0'", _, 0'") :- !.
  432escape(0'\\, _, 0'\\) :- !.
  433escape(0'/, _, 0'/) :- !.
  434escape(0'b, _, 0'\b) :- !.
  435escape(0'f, _, 0'\f) :- !.
  436escape(0'n, _, 0'\n) :- !.
  437escape(0'r, _, 0'\r) :- !.
  438escape(0't, _, 0'\t) :- !.
  439escape(0'u, Stream, C) :-
  440    get_XXXX(Stream, H),
  441    (   hi_surrogate(H)
  442    ->  get_surrogate_tail(Stream, H, C)
  443    ;   lo_surrogate(H)
  444    ->  syntax_error(illegal_surrogate_pair, Stream)
  445    ;   C = H
  446    ).
  447
  448get_XXXX(Stream, C) :-
  449    get_xdigit(Stream, D1),
  450    get_xdigit(Stream, D2),
  451    get_xdigit(Stream, D3),
  452    get_xdigit(Stream, D4),
  453    C is D1<<12+D2<<8+D3<<4+D4.
  454
  455get_xdigit(Stream, D) :-
  456    get_code(Stream, C),
  457    code_type(C, xdigit(D)),
  458    !.
  459get_xdigit(Stream, _) :-
  460    syntax_error(hexdigit_expected, Stream).
  461
  462get_surrogate_tail(Stream, Hi, Codepoint) :-
  463    (   get_code(Stream, 0'\\),
  464        get_code(Stream, 0'u),
  465        get_XXXX(Stream, Lo),
  466        surrogate([Hi, Lo], Codepoint)
  467    ->  true
  468    ;   syntax_error(illegal_surrogate_pair, Stream)
  469    ).
  470
  471
  472hi_surrogate(C) :-
  473    C >= 0xD800, C < 0xDC00.
  474
  475lo_surrogate(C) :-
  476    C >= 0xDC00, C < 0xE000.
  477
  478surrogate([Hi, Lo], Codepoint) :-
  479    hi_surrogate(Hi),
  480    lo_surrogate(Lo),
  481    Codepoint is (Hi - 0xD800) * 0x400 + (Lo - 0xDC00) + 0x10000.
  482
  483json_read_constant(0't, Stream, true) :-
  484    !,
  485    must_see(`rue`, Stream, true).
  486json_read_constant(0'f, Stream, false) :-
  487    !,
  488    must_see(`alse`, Stream, false).
  489json_read_constant(0'n, Stream, null) :-
  490    !,
  491    must_see(`ull`, Stream, null).
  492
  493must_see([], _Stream, _).
  494must_see([H|T], Stream, Name) :-
  495    get_code(Stream, C),
  496    (   C == H
  497    ->  true
  498    ;   syntax_error(json_expected(Name), Stream)
  499    ),
  500    must_see(T, Stream, Name).
  501
  502json_constant(true, Constant, Options) :-
  503    !,
  504    json_options_true(Options, Constant).
  505json_constant(false, Constant, Options) :-
  506    !,
  507    json_options_false(Options, Constant).
  508json_constant(null, Constant, Options) :-
  509    !,
  510    json_options_null(Options, Constant).
 ws(+Stream, -Next) is det
 ws(+C0, +Stream, -Next)
Skip white space on the Stream, returning the first non-ws character. Also skips // ... comments.
  518ws(Stream, Next) :-
  519    get_code(Stream, C0),
  520    json_skip_ws(Stream, C0, Next).
  521
  522ws(C0, Stream, Next) :-
  523    json_skip_ws(Stream, C0, Next).
  524
  525syntax_error(Message, Stream) :-
  526    stream_error_context(Stream, Context),
  527    throw(error(syntax_error(json(Message)), Context)).
  528
  529stream_error_context(Stream, stream(Stream, Line, LinePos, CharNo)) :-
  530    stream_pair(Stream, Read, _),
  531    character_count(Read, CharNo),
  532    line_position(Read, LinePos),
  533    line_count(Read, Line).
  534
  535
  536                 /*******************************
  537                 *          JSON OUTPUT         *
  538                 *******************************/
 json_write_string(+Stream, +Text) is det
Write a JSON string to Stream. Stream must be opened in a Unicode capable encoding, typically UTF-8.
  545% foreign json_write_string/2.
 json_write_indent(+Stream, +Indent, +TabDistance) is det
Newline and indent to Indent. A Newline is only written if line_position(Stream, Pos) is not 0. Then it writes Indent // TabDistance tab characters and Indent mode TabDistance spaces.
  553% foreign json_write_indent/3.
 json_write(+Stream, +Term) is det
 json_write(+Stream, +Term, +Options) is det
Write a JSON term to Stream. The JSON object is of the same format as produced by json_read/2, though we allow for some more flexibility with regard to pairs in objects. All of Name=Value, Name-Value and Name(Value) produce the same output.

Values can be of the form #(Term), which causes Term to be stringified if it is not an atom or string. Stringification is based on term_string/2.

Rational numbers are emitted as floating point numbers. The hook json_write_hook/4 can be used to realize domain specific alternatives.

The version 7 dict type is supported as well. Optionally, if the dict has a tag, a property "type":"tag" can be added to the object. This behaviour can be controlled using the tag option (see below). For example:

?- json_write(current_output, point{x:1,y:2}).
{
  "x":1,
  "y":2
}
?- json_write(current_output, point{x:1,y:2}, [tag(type)]).
{
  "type":"point",
  "x":1,
  "y":2
}

In addition to the options recognised by json_read/3, we process the following options are recognised:

width(+Width)
Width in which we try to format the result. Too long lines switch from horizontal to vertical layout for better readability. If performance is critical and human readability is not an issue use Width = 0, which causes a single-line output.
step(+Step)
Indentation increment for next level. Default is 2.
tab(+TabDistance)
Distance between tab-stops. If equal to Step, layout is generated with one tab per level.
non_finite(+How)
JSON has no representation for the floating point values infinity and NaN. How is one of error (default), raising a domain error, null, writing these values as null or json5, writing them as the JSON5 tokens Infinity, -Infinity and NaN.
serialize_unknown(+Boolean)
If true (default false), serialize unknown terms and print them as a JSON string. The default raises a type error. Note that this option only makes sense if you can guarantee that the passed value is not an otherwise valid Prolog representation of a Prolog term.

If a string is emitted, the sequence </ is emitted as <\/, <! as <\u0021 and the characters U+2028 and U+2029 are escaped. This is valid JSON syntax which ensures that JSON objects can be safely embedded into an HTML <script> element.

Integer keys, as may appear in dicts, are written as strings.

Errors
- domain_error(acyclic_term, Term) if Term is cyclic.
 json_write_hook(+Term, +Stream, +State, +Options) is semidet
Hook that can be used to emit a JSON representation for Term to Stream. If the predicate succeeds it must have written a valid JSON data element and if it fails it may not have produced any output. This facility may be used to map arbitrary Prolog terms to JSON. It was added to manage the precision with which floating point numbers are emitted.

Note that this hook is shared by all users of this library. It is generally advised to map a unique compound term to avoid interference with normal output.

Arguments:
State- and Options are opaque handles to the current output state and settings. Future versions may provide documented access to these terms. Currently it is advised to ignore these arguments.
 json_dict_pairs(+Dict, -Pairs) is semidet
This hook may be used to order the keys of an object. If it fails, dict_pairs/3 is used which produces an ordered list of keys.
  656:- record json_write_state(indent:nonneg = 0,
  657                           step:positive_integer = 2,
  658                           tab:positive_integer = 8,
  659                           width:nonneg = 72,
  660                           serialize_unknown:boolean = false
  661                          ).  662
  663json_write(Stream, Term) :-
  664    json_write(Stream, Term, []).
  665json_write(Stream, Term, Options) :-
  666    must_be(acyclic, Term),
  667    make_json_write_state(Options, State, Options1),
  668    make_json_options(Options1, OptionTerm, _RestOptions),
  669    json_write_term(Term, Stream, State, OptionTerm).
  670
  671json_write_term(Var, _, _, _) :-
  672    var(Var),
  673    !,
  674    instantiation_error(Var).
  675json_write_term(json(Pairs), Stream, State, Options) :-
  676    !,
  677    json_write_object(Pairs, Stream, State, Options).
  678json_write_term(Dict, Stream, State, Options) :-
  679    is_dict(Dict, Tag),
  680    !,
  681    json_pairs(Dict, Pairs0),
  682    (   nonvar(Tag),
  683        json_options_tag(Options, Name),
  684        Name \== ''
  685    ->  Pairs = [Name-Tag|Pairs0]
  686    ;   Pairs = Pairs0
  687    ),
  688    json_write_object(Pairs, Stream, State, Options).
  689json_write_term(List, Stream, State, Options) :-
  690    is_list(List),
  691    !,
  692    space_if_not_at_left_margin(Stream, State),
  693    write(Stream, '['),
  694    (   json_write_state_width(State, Width),
  695        (   Width == 0
  696        ->  true
  697        ;   json_write_state_indent(State, Indent),
  698            json_print_length(List, Options, Width, Indent, _)
  699        )
  700    ->  set_width_of_json_write_state(0, State, State2),
  701        write_array_hor(List, Stream, State2, Options),
  702        write(Stream, ']')
  703    ;   step_indent(State, State2),
  704        write_array_ver(List, Stream, State2, Options),
  705        indent(Stream, State),
  706        write(Stream, ']')
  707    ).
  708
  709json_write_term(Term, Stream, State, Options) :-
  710    json_write_hook(Term, Stream, State, Options),
  711    !.
  712json_write_term(Number, Stream, _State, Options) :-
  713    number(Number),
  714    !,
  715    (   integer(Number)
  716    ->  write(Stream, Number)
  717    ;   Float is float(Number),             % float or rational number
  718        (   finite_float(Float)
  719        ->  write(Stream, Float)
  720        ;   json_options_non_finite(Options, How),
  721            json_write_non_finite(How, Float, Stream)
  722        )
  723    ).
  724json_write_term(True, Stream, _State, Options) :-
  725    json_options_true(Options, True),
  726    !,
  727    write(Stream, true).
  728json_write_term(False, Stream, _State, Options) :-
  729    json_options_false(Options, False),
  730    !,
  731    write(Stream, false).
  732json_write_term(Null, Stream, _State, Options) :-
  733    json_options_null(Options, Null),
  734    !,
  735    write(Stream, null).
  736json_write_term(#(Text), Stream, _State, _Options) :-
  737    !,
  738    (   (   atom(Text)
  739        ;   string(Text)
  740        )
  741    ->  json_write_string(Stream, Text)
  742    ;   term_string(Text, String),
  743        json_write_string(Stream, String)
  744    ).
  745json_write_term(String, Stream, _State, _Options) :-
  746    atom(String),
  747    !,
  748    json_write_string(Stream, String).
  749json_write_term(String, Stream, _State, _Options) :-
  750    string(String),
  751    !,
  752    json_write_string(Stream, String).
  753json_write_term(AnyTerm, Stream, State, _Options) :-
  754    (   json_write_state_serialize_unknown(State, true)
  755    ->  term_string(AnyTerm, String),
  756        json_write_string(Stream, String)
  757    ;   type_error(json_term, AnyTerm)
  758    ).
  759
  760finite_float(Float) :-
  761    float_class(Float, Class),
  762    Class \== nan,
  763    Class \== infinite.
  764
  765json_write_non_finite(error, Float, _) :-
  766    domain_error(json_number, Float).
  767json_write_non_finite(null, _, Stream) :-
  768    write(Stream, null).
  769json_write_non_finite(json5, Float, Stream) :-
  770    (   float_class(Float, nan)
  771    ->  write(Stream, 'NaN')
  772    ;   Float > 0
  773    ->  write(Stream, 'Infinity')
  774    ;   write(Stream, '-Infinity')
  775    ).
  776
  777json_pairs(Dict, Pairs) :-
  778    json_dict_pairs(Dict, Pairs),
  779    !.
  780json_pairs(Dict, Pairs) :-
  781    dict_pairs(Dict, _, Pairs).
  782
  783json_write_object(Pairs, Stream, State, Options) :-
  784    space_if_not_at_left_margin(Stream, State),
  785    write(Stream, '{'),
  786    (   json_write_state_width(State, Width),
  787        (   Width == 0
  788        ->  true
  789        ;   json_write_state_indent(State, Indent),
  790            json_print_length(json(Pairs), Options, Width, Indent, _)
  791        )
  792    ->  set_width_of_json_write_state(0, State, State2),
  793        write_pairs_hor(Pairs, Stream, State2, Options),
  794        write(Stream, '}')
  795    ;   step_indent(State, State2),
  796        write_pairs_ver(Pairs, Stream, State2, Options),
  797        indent(Stream, State),
  798        write(Stream, '}')
  799    ).
  800
  801
  802write_pairs_hor([], _, _, _).
  803write_pairs_hor([H|T], Stream, State, Options) :-
  804    json_pair(H, Name, Value),
  805    json_write_string(Stream, Name),
  806    write(Stream, ':'),
  807    json_write_term(Value, Stream, State, Options),
  808    (   T == []
  809    ->  true
  810    ;   (   json_write_state_width(State, 0)
  811        ->  write(Stream, ',')
  812        ;   write(Stream, ', ')
  813        ),
  814        write_pairs_hor(T, Stream, State, Options)
  815    ).
  816
  817write_pairs_ver([], _, _, _).
  818write_pairs_ver([H|T], Stream, State, Options) :-
  819    indent(Stream, State),
  820    json_pair(H, Name, Value),
  821    json_write_string(Stream, Name),
  822    write(Stream, ':'),
  823    json_write_term(Value, Stream, State, Options),
  824    (   T == []
  825    ->  true
  826    ;   write(Stream, ','),
  827        write_pairs_ver(T, Stream, State, Options)
  828    ).
  829
  830
  831json_pair(Var, _, _) :-
  832    var(Var),
  833    !,
  834    instantiation_error(Var).
  835json_pair(Name=Value, Name, Value) :- !.
  836json_pair(Name-Value, Name, Value) :- !.
  837json_pair(NameValue, Name, Value) :-
  838    compound(NameValue),
  839    NameValue =.. [Name, Value],
  840    !.
  841json_pair(Pair, _, _) :-
  842    type_error(json_pair, Pair).
  843
  844
  845write_array_hor([], _, _, _).
  846write_array_hor([H|T], Stream, State, Options) :-
  847    json_write_term(H, Stream, State, Options),
  848    (   T == []
  849    ->  write(Stream, ' ')
  850    ;   write(Stream, ', '),
  851        write_array_hor(T, Stream, State, Options)
  852    ).
  853
  854write_array_ver([], _, _, _).
  855write_array_ver([H|T], Stream, State, Options) :-
  856    indent(Stream, State),
  857    json_write_term(H, Stream, State, Options),
  858    (   T == []
  859    ->  true
  860    ;   write(Stream, ','),
  861        write_array_ver(T, Stream, State, Options)
  862    ).
  863
  864
  865indent(Stream, State) :-
  866    json_write_state_indent(State, Indent),
  867    json_write_state_tab(State, Tab),
  868    json_write_indent(Stream, Indent, Tab).
  869
  870step_indent(State0, State) :-
  871    json_write_state_indent(State0, Indent),
  872    json_write_state_step(State0, Step),
  873    NewIndent is Indent+Step,
  874    set_indent_of_json_write_state(NewIndent, State0, State).
  875
  876space_if_not_at_left_margin(Stream, State) :-
  877    stream_pair(Stream, _, Write),
  878    line_position(Write, LinePos),
  879    (   LinePos == 0
  880    ;   json_write_state_indent(State, LinePos)
  881    ),
  882    !.
  883space_if_not_at_left_margin(Stream, _) :-
  884    put_char(Stream, ' ').
 json_print_length(+Value, +Options, +Max, +Len0, +Len) is semidet
True if Len-Len0 is the print-length of Value on a single line and Len-Len0 =< Max.
To be done
- Escape sequences in strings are not considered.
  894json_print_length(Var, _, _, _, _) :-
  895    var(Var),
  896    !,
  897    instantiation_error(Var).
  898json_print_length(json(Pairs), Options, Max, Len0, Len) :-
  899    !,
  900    Len1 is Len0 + 2,
  901    Len1 =< Max,
  902    must_be(list, Pairs),
  903    pairs_print_length(Pairs, Options, Max, Len1, Len).
  904json_print_length(Dict, Options, Max, Len0, Len) :-
  905    is_dict(Dict),
  906    !,
  907    dict_pairs(Dict, _Tag, Pairs),
  908    Len1 is Len0 + 2,
  909    Len1 =< Max,
  910    pairs_print_length(Pairs, Options, Max, Len1, Len).
  911json_print_length(Array, Options, Max, Len0, Len) :-
  912    is_list(Array),
  913    !,
  914    Len1 is Len0 + 2,
  915    Len1 =< Max,
  916    array_print_length(Array, Options, Max, Len1, Len).
  917json_print_length(Null, Options, Max, Len0, Len) :-
  918    json_options_null(Options, Null),
  919    !,
  920    Len is Len0 + 4,
  921    Len =< Max.
  922json_print_length(False, Options, Max, Len0, Len) :-
  923    json_options_false(Options, False),
  924    !,
  925    Len is Len0 + 5,
  926    Len =< Max.
  927json_print_length(True, Options, Max, Len0, Len) :-
  928    json_options_true(Options, True),
  929    !,
  930    Len is Len0 + 4,
  931    Len =< Max.
  932json_print_length(Number, _Options, Max, Len0, Len) :-
  933    number(Number),
  934    !,
  935    (   float(Number),
  936        \+ finite_float(Number)
  937    ->  AL = 9                              % -Infinity
  938    ;   write_size(Number, AL, _H, [])
  939    ),
  940    Len is Len0 + AL,
  941    Len =< Max.
  942json_print_length(@(Id), _Options, Max, Len0, Len) :-
  943    atom(Id),
  944    !,
  945    atom_length(Id, IdLen),
  946    Len is Len0+IdLen,
  947    Len =< Max.
  948json_print_length(String, _Options, Max, Len0, Len) :-
  949    string_len(String, Len0, Len),
  950    !,
  951    Len =< Max.
  952json_print_length(AnyTerm, _Options, Max, Len0, Len) :-
  953    write_size(AnyTerm, AL, _H, []),          % will be serialized
  954    Len is Len0 + AL+2,
  955    Len =< Max.
  956
  957pairs_print_length([], _, _, Len, Len).
  958pairs_print_length([H|T], Options, Max, Len0, Len) :-
  959    pair_len(H, Options, Max, Len0, Len1),
  960    (   T == []
  961    ->  Len = Len1
  962    ;   Len2 is Len1 + 2,
  963        Len2 =< Max,
  964        pairs_print_length(T, Options, Max, Len2, Len)
  965    ).
  966
  967pair_len(Pair, Options, Max, Len0, Len) :-
  968    compound(Pair),
  969    pair_nv(Pair, Name, Value),
  970    !,
  971    string_len(Name, Len0, Len1),
  972    Len2 is Len1+2,
  973    Len2 =< Max,
  974    json_print_length(Value, Options, Max, Len2, Len).
  975pair_len(Pair, _Options, _Max, _Len0, _Len) :-
  976    type_error(pair, Pair).
  977
  978pair_nv(Name=Value, Name, Value) :- !.
  979pair_nv(Name-Value, Name, Value) :- !.
  980pair_nv(Term, Name, Value) :-
  981    compound_name_arguments(Term, Name, [Value]).
  982
  983array_print_length([], _, _, Len, Len).
  984array_print_length([H|T], Options, Max, Len0, Len) :-
  985    json_print_length(H, Options, Max, Len0, Len1),
  986    (   T == []
  987    ->  Len = Len1
  988    ;   Len2 is Len1+2,
  989        Len2 =< Max,
  990        array_print_length(T, Options, Max, Len2, Len)
  991    ).
  992
  993string_len(String, Len0, Len) :-
  994    atom(String),
  995    !,
  996    atom_length(String, AL),
  997    Len is Len0 + AL + 2.
  998string_len(String, Len0, Len) :-
  999    string(String),
 1000    !,
 1001    string_length(String, AL),
 1002    Len is Len0 + AL + 2.
 1003string_len(Int, Len0, Len) :-               % Integer dict key
 1004    integer(Int),
 1005    !,
 1006    write_size(Int, AL, _, []),
 1007    Len is Len0 + AL + 2.
 1008
 1009
 1010                 /*******************************
 1011                 *             TEST             *
 1012                 *******************************/
 is_json_term(@Term) is semidet
 is_json_term(@Term, +Options) is semidet
True if Term is a json term. Options are the same as for json_read/2, defining the Prolog representation for the JSON true, false and null constants.
 1021is_json_term(Term) :-
 1022    default_json_options(Options),
 1023    is_json_term2(Options, Term).
 1024
 1025is_json_term(Term, Options) :-
 1026    make_json_options(Options, OptionTerm, _RestOptions),
 1027    is_json_term2(OptionTerm, Term).
 1028
 1029is_json_term2(_, Var) :-
 1030    var(Var), !, fail.
 1031is_json_term2(Options, json(Pairs)) :-
 1032    !,
 1033    is_list(Pairs),
 1034    maplist(is_json_pair(Options), Pairs).
 1035is_json_term2(Options, List) :-
 1036    is_list(List),
 1037    !,
 1038    maplist(is_json_term2(Options), List).
 1039is_json_term2(_, Primitive) :-
 1040    atomic(Primitive),
 1041    !.           % atom, string or number
 1042is_json_term2(Options, True) :-
 1043    json_options_true(Options, True).
 1044is_json_term2(Options, False) :-
 1045    json_options_false(Options, False).
 1046is_json_term2(Options, Null) :-
 1047    json_options_null(Options, Null).
 1048
 1049is_json_pair(_, Var) :-
 1050    var(Var), !, fail.
 1051is_json_pair(Options, Name=Value) :-
 1052    atom(Name),
 1053    is_json_term2(Options, Value).
 1054
 1055                 /*******************************
 1056                 *         DICT SUPPORT         *
 1057                 *******************************/
 json_read_dict(+Stream, -Dict) is det
 json_read_dict(+Stream, -Dict, +Options) is det
Read a JSON object, returning objects as a dicts. The representation depends on the options, where the default is:

The predicate json_read_dict/3 processes the same options as json_read/3, but with different defaults. In addition, it processes the tag option. See json_read/3 for details about the shared options.

tag(+Name)
When converting to/from a dict, map the indicated JSON attribute to the dict tag. No mapping is performed if Name is the empty atom ('', default). See json_read_dict/2 and json_write_dict/2.
default_tag(+Tag)
Provide the default tag if the above tag option does not apply.
null(+NullTerm)
Default the atom null.
true(+TrueTerm)
Default the atom true.
false(+FalseTerm)
Default the atom false
end_of_file(+ErrorOrTerm)
Action on reading end-of-file. See json_read/3 for details.
value_string_as(+Type)
Prolog type used for strings used as value. Default is string. The alternative is atom, producing a packed string object.
 1098json_read_dict(Stream, Dict) :-
 1099    json_read_dict(Stream, Dict, []).
 1100
 1101json_read_dict(Stream, Dict, Options) :-
 1102    make_json_dict_options(Options, OptionTerm, _RestOptions),
 1103    (   json_value_top(Stream, Term, OptionTerm)
 1104    ->  true
 1105    ;   syntax_error(illegal_json, Stream)
 1106    ),
 1107    term_to_dict(Term, Dict, OptionTerm).
 1108
 1109term_to_dict(Var, Var, _Options) :-
 1110    var(Var),
 1111    !.
 1112term_to_dict(json(Pairs), Dict, Options) :-
 1113    !,
 1114    (   json_options_tag(Options, TagName),
 1115        TagName \== '',
 1116        select(TagName = Tag0, Pairs, NVPairs),
 1117        to_atom(Tag0, Tag)
 1118    ->  json_dict_pairs(NVPairs, DictPairs, Options)
 1119    ;   json_options_default_tag(Options, DefTag),
 1120        (   var(DefTag)
 1121        ->  true
 1122        ;   Tag = DefTag
 1123        ),
 1124        json_dict_pairs(Pairs, DictPairs, Options)
 1125    ),
 1126    dict_create(Dict, Tag, DictPairs).
 1127term_to_dict(Value0, Value, _Options) :-
 1128    atomic(Value0), Value0 \== [],
 1129    !,
 1130    Value = Value0.
 1131term_to_dict(List0, List, Options) :-
 1132    is_list(List0),
 1133    !,
 1134    terms_to_dicts(List0, List, Options).
 1135term_to_dict(Special, Special, Options) :-
 1136    (   json_options_true(Options, Special)
 1137    ;   json_options_false(Options, Special)
 1138    ;   json_options_null(Options, Special)
 1139    ;   json_options_end_of_file(Options, Special)
 1140    ),
 1141    !.
 1142
 1143json_dict_pairs([], [], _).
 1144json_dict_pairs([Name=Value0|T0], [Name=Value|T], Options) :-
 1145    term_to_dict(Value0, Value, Options),
 1146    json_dict_pairs(T0, T, Options).
 1147
 1148terms_to_dicts([], [], _).
 1149terms_to_dicts([Value0|T0], [Value|T], Options) :-
 1150    term_to_dict(Value0, Value, Options),
 1151    terms_to_dicts(T0, T, Options).
 1152
 1153to_atom(Tag, Atom) :-
 1154    string(Tag),
 1155    !,
 1156    atom_string(Atom, Tag).
 1157to_atom(Atom, Atom) :-
 1158    atom(Atom).
 json_write_dict(+Stream, +Dict) is det
 json_write_dict(+Stream, +Dict, +Options) is det
Write a JSON term, represented using dicts. This is the same as json_write/3, but assuming the default representation of JSON objects as dicts.
 1167json_write_dict(Stream, Dict) :-
 1168    json_write_dict(Stream, Dict, []).
 1169
 1170json_write_dict(Stream, Dict, Options) :-
 1171    must_be(acyclic, Dict),
 1172    make_json_write_state(Options, State, Options1),
 1173    make_json_dict_options(Options1, OptionTerm, _RestOptions),
 1174    json_write_term(Dict, Stream, State, OptionTerm).
 1175
 1176
 1177make_json_dict_options(Options, Record, RestOptions) :-
 1178    default_json_dict_options(Record0),
 1179    set_json_options_fields(Options, Record0, Record, RestOptions).
 atom_json_dict(+Atom, -JSONDict, +Options) is det
atom_json_dict(-Text, +JSONDict, +Options) is det
Convert between textual representation and a JSON term represented as a dict. Options are as for json_read_dict/3. In write mode, the additional option
as(Type)
defines the output type, which is one of atom, string or codes.
 1192atom_json_dict(Atom, Term, Options) :-
 1193    ground(Atom),
 1194    !,
 1195    setup_call_cleanup(
 1196        open_string(Atom, In),
 1197        json_read_dict(In, Term, Options),
 1198        close(In)).
 1199atom_json_dict(Result, Term, Options) :-
 1200    select_option(as(Type), Options, Options1, atom),
 1201    (   type_term(Type, Result, Out)
 1202    ->  true
 1203    ;   must_be(oneof([atom,string,codes]), Type)
 1204    ),
 1205    with_output_to(Out,
 1206                   json_write_dict(current_output, Term, Options1)).
 1207
 1208                 /*******************************
 1209                 *      QUASI-QUOTATIONS        *
 1210                 *******************************/
 json(+Content, +Vars, +VarDict, -JSON) is det
The predicate json/4 implements JSON quasi quotations. These quotations produce a JSON dict that is suitable for json_write_dict/2. The quasi quoter only accepts valid, but possibly partial JSON documents. The quoter replaces content whose value is a Prolog variable that appears in the argument list of the json indicator. Notably, you can't use a Prolog variable in place of an object key. Here is an example.
  {|json(Name)||
      { "name": Name,
        "created": {
          "day":null,
          "month":"December",
          "year":2007
        },
        "confirmed":true,
        "members":[1,2,3]
      }
  |}.
 1236:- quasi_quotation_syntax(json). 1237
 1238json(Content, Vars, Dict, Result) :-
 1239    must_be(list, Dict),
 1240    include(qq_var(Vars), Dict, QQDict),
 1241    with_quasi_quotation_input(Content, Stream,
 1242                               json_read_dict(Stream, Result,
 1243                                              [ qqdict(QQDict)
 1244                                              ])).
 1245
 1246qq_var(Vars, _=Var) :-
 1247    member(V, Vars),
 1248    V == Var,
 1249    !.
 1250
 1251
 1252                 /*******************************
 1253                 *           MESSAGES           *
 1254                 *******************************/
 1255
 1256:- multifile
 1257    prolog:error_message/3. 1258
 1259prolog:error_message(syntax_error(json(Id))) -->
 1260    [ 'JSON syntax error: ' ],
 1261    json_syntax_error(Id).
 1262
 1263json_syntax_error(illegal_comment) -->
 1264    [ 'Illegal comment' ].
 1265json_syntax_error(illegal_string_escape) -->
 1266    [ 'Illegal escape sequence in string' ].
 1267json_syntax_error(illegal_surrogate_pair) -->
 1268    [ 'Illegal escaped surrogate pair in string' ].
 1269json_syntax_error(non_existing_var(Var, QQDict)) -->
 1270    { maplist(arg(1), QQDict, Vars),
 1271      Term =.. [json|Vars]
 1272    },
 1273    [ 'Variable ', ansi(code, '~w', [Var]),
 1274      ' is not defined in {|',ansi(code,'~w',Term),'|||}'
 1275    ].
 1276
 1277                /*******************************
 1278                *           SANDBOX            *
 1279                *******************************/
 1280
 1281:- multifile sandbox:safe_primitive/1. 1282
 1283sandbox:safe_primitive(json:json(_,_,_,_))