View source with formatted 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                     ]).  106
  107/** <module> Reading and writing JSON serialization
  108
  109This module supports reading and  writing   JSON  objects.  This library
  110supports two Prolog representations (the   _new_  representation is only
  111supported in SWI-Prolog version 7 and later):
  112
  113  - The *classical* representation is provided by json_read/3 and
  114    json_write/3.  This represents a JSON object as json(NameValueList),
  115    a JSON string as an atom and the JSON constants `null`, `true` and
  116    `false` as @(null), @(true) and @false.
  117
  118  - The *new* representation is provided by json_read_dict/3 and
  119    json_write_dict/3. This represents a JSON object as a dict, a JSON
  120    string as a Prolog string and the JSON constants using the Prolog
  121    atoms `null`, `true` and `false`.
  122
  123This module provides the `json` _Quasi Quotation_ syntax that allows for
  124embedding JSON documents in Prolog.
  125
  126@see    http_json.pl links JSON to the HTTP client and server modules.
  127@see    json_convert.pl converts JSON Prolog terms to more comfortable
  128terms.
  129*/
  130
  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                 *******************************/
  149
  150%!  atom_json_term(?Atom, ?JSONTerm, +Options) is det.
  151%
  152%   Convert between textual  representation  and   a  JSON  term. In
  153%   _write_ mode (JSONTerm to Atom), the option
  154%
  155%       * as(Type)
  156%       defines the output type, which is one of `atom` (default),
  157%       `string`, `codes` or `chars`.
  158
  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                 *******************************/
  184
  185%!  json_read(+Stream, -Term) is det.
  186%!  json_read(+Stream, -Term, +Options) is det.
  187%
  188%   Read next JSON value from Stream into a Prolog term. The
  189%   canonical representation for Term is:
  190%
  191%     * A JSON object is mapped to a term json(NameValueList), where
  192%       NameValueList is a list of Name=Value. Name is an atom
  193%       created from the JSON string.
  194%
  195%     * A JSON array is mapped to a Prolog list of JSON values.
  196%
  197%     * A JSON string is mapped to a Prolog atom
  198%
  199%     * A JSON number is mapped to a Prolog number
  200%
  201%     * The JSON constants `true` and `false` are mapped -like JPL-
  202%       to @(true) and @(false).
  203%
  204%     * The JSON constant `null` is mapped to the Prolog term
  205%       @(null)
  206%
  207%   Here is a complete example in  JSON and its corresponding Prolog
  208%   term.
  209%
  210%     ```
  211%     { "name":"Demo term",
  212%       "created": {
  213%         "day":null,
  214%         "month":"December",
  215%         "year":2007
  216%       },
  217%       "confirmed":true,
  218%       "members":[1,2,3]
  219%     }
  220%     ```
  221%
  222%     ```
  223%     json([ name='Demo term',
  224%            created=json([day= @null, month='December', year=2007]),
  225%            confirmed= @true,
  226%            members=[1, 2, 3]
  227%          ])
  228%     ```
  229%
  230%   The following options are processed:
  231%
  232%     - null(+NullTerm)
  233%       Term used to represent JSON `null`.  Default @(null)
  234%     - true(+TrueTerm)
  235%       Term used to represent JSON `true`.  Default @(true)
  236%     - false(+FalseTerm)
  237%       Term used to represent JSON `false`.  Default @(false)
  238%     - end_of_file(+ErrorOrTerm)
  239%       If end of file is reached after skipping white space
  240%       but before any input is processed take the following
  241%       action (default `error`):
  242%         - If ErrorOrTerm == `error`, throw an unexpected
  243%           end of file syntax error
  244%         - Otherwise return ErrorOrTerm.
  245%       Returning an status term is required to process
  246%       [Concatenated
  247%       JSON](https://en.wikipedia.org/wiki/JSON_streaming#Concatenated_JSON).
  248%       Suggested values are `@(eof)` or `end_of_file`.
  249%     - value_string_as(+Type)
  250%       Prolog type used for strings used as value. Default is `atom`.
  251%       The alternative is `string`, producing a packed string object.
  252%       Please note that `codes` or `chars` would produce ambiguous
  253%       output and are therefore not supported.
  254%     - non_finite(+How)
  255%       JSON does not support the floating point values infinity and
  256%       NaN.  If How is `json5`, accept the JSON5 tokens `Infinity`,
  257%       `-Infinity` and `NaN`.  Otherwise (default `error`), these are
  258%       syntax errors.
  259%
  260%   @see    json_read_dict/3 to read a JSON term using the version 7
  261%           extended data types.
  262
  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).
  511
  512%!  ws(+Stream, -Next) is det.
  513%!  ws(+C0, +Stream, -Next)
  514%
  515%   Skip white space on the Stream, returning the first non-ws
  516%   character.  Also skips =|//|= ... comments.
  517
  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                 *******************************/
  539
  540%!  json_write_string(+Stream, +Text) is det.
  541%
  542%   Write a JSON string to  Stream.  Stream   must  be  opened  in a
  543%   Unicode capable encoding, typically UTF-8.
  544
  545% foreign json_write_string/2.
  546
  547%!  json_write_indent(+Stream, +Indent, +TabDistance) is det.
  548%
  549%   Newline and indent to  Indent.  A   Newline  is  only written if
  550%   line_position(Stream, Pos) is not 0. Then   it  writes Indent //
  551%   TabDistance tab characters and Indent mode TabDistance spaces.
  552
  553% foreign json_write_indent/3.
  554
  555%!  json_write(+Stream, +Term) is det.
  556%!  json_write(+Stream, +Term, +Options) is det.
  557%
  558%   Write a JSON term to Stream. The JSON   object is of the same format
  559%   as  produced  by  json_read/2,  though  we    allow  for  some  more
  560%   flexibility with regard to pairs  in   objects.  All  of Name=Value,
  561%   Name-Value and Name(Value) produce the same output.
  562%
  563%   Values can be of  the  form  #(Term),   which  causes  `Term`  to be
  564%   _stringified_ if it is not  an   atom  or string. Stringification is
  565%   based on term_string/2.
  566%
  567%   Rational numbers are emitted as  floating   point  numbers. The hook
  568%   json_write_hook/4  can  be  used   to    realize   domain   specific
  569%   alternatives.
  570%
  571%   The version 7 _dict_ type is supported   as well. Optionally, if the
  572%   dict has a _tag_, a  property  "type":"tag"   can  be  added  to the
  573%   object. This behaviour can be controlled using the `tag` option (see
  574%   below). For example:
  575%
  576%     ==
  577%     ?- json_write(current_output, point{x:1,y:2}).
  578%     {
  579%       "x":1,
  580%       "y":2
  581%     }
  582%     ==
  583%
  584%     ==
  585%     ?- json_write(current_output, point{x:1,y:2}, [tag(type)]).
  586%     {
  587%       "type":"point",
  588%       "x":1,
  589%       "y":2
  590%     }
  591%     ==
  592%
  593%   In addition to the options recognised by json_read/3, we process
  594%   the following options are recognised:
  595%
  596%       * width(+Width)
  597%       Width in which we try to format the result.  Too long lines
  598%       switch from _horizontal_ to _vertical_ layout for better
  599%       readability. If performance is critical and human
  600%       readability is not an issue use Width = 0, which causes a
  601%       single-line output.
  602%
  603%       * step(+Step)
  604%       Indentation increment for next level.  Default is 2.
  605%
  606%       * tab(+TabDistance)
  607%       Distance between tab-stops.  If equal to Step, layout
  608%       is generated with one tab per level.
  609%
  610%       * non_finite(+How)
  611%       JSON has no representation for the floating point values
  612%       infinity and NaN.  How is one of `error` (default), raising
  613%       a domain error, `null`, writing these values as `null` or
  614%       `json5`, writing them as the JSON5 tokens `Infinity`,
  615%       `-Infinity` and `NaN`.
  616%
  617%       * serialize_unknown(+Boolean)
  618%       If `true` (default `false`), serialize unknown terms and
  619%       print them as a JSON string.  The default raises a type
  620%       error.  Note that this option only makes sense if you can
  621%       guarantee that the passed value is not an otherwise valid
  622%       Prolog representation of a Prolog term.
  623%
  624%   If a string is  emitted,  the   sequence  =|</|=  is  emitted as
  625%   =|<\/|=, =|<!|= as =|<\u0021|= and the characters U+2028 and U+2029
  626%   are escaped. This is valid  JSON  syntax   which  ensures  that JSON
  627%   objects  can  be  safely  embedded  into  an  HTML  =|<script>|=
  628%   element.
  629%
  630%   Integer keys, as may appear in dicts, are written as strings.
  631%
  632%   @error domain_error(acyclic_term, Term) if Term is cyclic.
  633
  634%!  json_write_hook(+Term, +Stream, +State, +Options) is semidet.
  635%
  636%   Hook that can be used to  emit   a  JSON  representation for Term to
  637%   Stream. If the  predicate  succeeds  it   __must__  have  written  a
  638%   __valid__ JSON data element and if it fails it may not have produced
  639%   any output. This facility may be used  to map arbitrary Prolog terms
  640%   to JSON. It was added to manage   the  precision with which floating
  641%   point numbers are emitted.
  642%
  643%   Note that this hook is shared by all   users  of this library. It is
  644%   generally  advised  to  map  a  unique    compound   term  to  avoid
  645%   interference with normal output.
  646%
  647%   @arg State and Options are opaque handles to the current output
  648%   state and settings.  Future versions may provide documented access
  649%   to these terms.  Currently it is advised to ignore these arguments.
  650
  651%!  json_dict_pairs(+Dict, -Pairs) is semidet.
  652%
  653%   This hook may be used to order the   keys of an object. If it fails,
  654%   dict_pairs/3 is used which produces an ordered list of keys.
  655
  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, ' ').
  885
  886
  887%!  json_print_length(+Value, +Options, +Max, +Len0, +Len) is semidet.
  888%
  889%   True if Len-Len0 is the print-length of Value on a single line
  890%   and Len-Len0 =< Max.
  891%
  892%   @tbd    Escape sequences in strings are not considered.
  893
  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                 *******************************/
 1013
 1014%!  is_json_term(@Term) is semidet.
 1015%!  is_json_term(@Term, +Options) is semidet.
 1016%
 1017%   True if Term is  a  json  term.   Options  are  the  same as for
 1018%   json_read/2, defining the Prolog  representation   for  the JSON
 1019%   `true`, `false` and `null` constants.
 1020
 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                 *******************************/
 1058
 1059%!  json_read_dict(+Stream, -Dict) is det.
 1060%!  json_read_dict(+Stream, -Dict, +Options) is det.
 1061%
 1062%   Read  a  JSON  object,  returning  objects    as  a  dicts.  The
 1063%   representation depends on the options, where the default is:
 1064%
 1065%     * String values are mapped to Prolog strings
 1066%     * JSON `true`, `false` and `null` are represented using these
 1067%       Prolog atoms.
 1068%     * JSON objects are mapped to dicts.
 1069%     * Optionally, a `type` field in an object assigns a tag for
 1070%       the dict.
 1071%
 1072%   The predicate json_read_dict/3 processes  the   same  options as
 1073%   json_read/3,  but  with  different  defaults.  In  addition,  it
 1074%   processes the `tag` option. See   json_read/3  for details about
 1075%   the shared options.
 1076%
 1077%     * tag(+Name)
 1078%       When converting to/from a dict, map the indicated JSON
 1079%       attribute to the dict _tag_. No mapping is performed if Name
 1080%       is the empty atom ('', default). See json_read_dict/2 and
 1081%       json_write_dict/2.
 1082%     * default_tag(+Tag)
 1083%       Provide the default tag if the above `tag` option does not
 1084%       apply.
 1085%     * null(+NullTerm)
 1086%       Default the atom `null`.
 1087%     * true(+TrueTerm)
 1088%       Default the atom `true`.
 1089%     * false(+FalseTerm)
 1090%       Default the atom `false`
 1091%     * end_of_file(+ErrorOrTerm)
 1092%       Action on reading end-of-file. See json_read/3 for details.
 1093%     * value_string_as(+Type)
 1094%       Prolog type used for strings used as value.  Default
 1095%       is `string`.  The alternative is `atom`, producing a
 1096%       packed string object.
 1097
 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).
 1159
 1160%!  json_write_dict(+Stream, +Dict) is det.
 1161%!  json_write_dict(+Stream, +Dict, +Options) is det.
 1162%
 1163%   Write a JSON term, represented using dicts.  This is the same as
 1164%   json_write/3, but assuming the default   representation  of JSON
 1165%   objects as dicts.
 1166
 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).
 1180
 1181%!  atom_json_dict(+Atom, -JSONDict, +Options) is det.
 1182%!  atom_json_dict(-Text, +JSONDict, +Options) is det.
 1183%
 1184%   Convert  between  textual  representation  and    a   JSON  term
 1185%   represented as a dict. Options are as for json_read_dict/3.
 1186%   In _write_ mode, the additional option
 1187%
 1188%       * as(Type)
 1189%       defines the output type, which is one of `atom`,
 1190%       `string` or `codes`.
 1191
 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                 *******************************/
 1211
 1212%!  json(+Content, +Vars, +VarDict, -JSON) is det.
 1213%
 1214%   The  predicate  json/4  implements  JSON   quasi  quotations.  These
 1215%   quotations   produce   a   JSON   dict    that   is   suitable   for
 1216%   json_write_dict/2. The quasi quoter only accepts valid, but possibly
 1217%   partial JSON documents. The quoter replaces content whose value is a
 1218%   Prolog variable that appears in  the   argument  list  of the `json`
 1219%   indicator. Notably, you can't use a Prolog   variable in place of an
 1220%   object key. Here is an example.
 1221%
 1222%     ```
 1223%       {|json(Name)||
 1224%           { "name": Name,
 1225%             "created": {
 1226%               "day":null,
 1227%               "month":"December",
 1228%               "year":2007
 1229%             },
 1230%             "confirmed":true,
 1231%             "members":[1,2,3]
 1232%           }
 1233%       |}.
 1234%     ```
 1235
 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(_,_,_,_))