View source with raw comments or as raw
   1:- encoding(utf8).
   2/*  Part of SWI-Prolog
   3
   4    Author:        Torbj��rn Lager and Jan Wielemaker
   5    E-mail:        J.Wielemaker@vu.nl
   6    WWW:           http://www.swi-prolog.org
   7    Copyright (c)  2014-2015, Torbj��rn Lager,
   8                              VU University Amsterdam
   9    All rights reserved.
  10
  11    Redistribution and use in source and binary forms, with or without
  12    modification, are permitted provided that the following conditions
  13    are met:
  14
  15    1. Redistributions of source code must retain the above copyright
  16       notice, this list of conditions and the following disclaimer.
  17
  18    2. Redistributions in binary form must reproduce the above copyright
  19       notice, this list of conditions and the following disclaimer in
  20       the documentation and/or other materials provided with the
  21       distribution.
  22
  23    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  24    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  25    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  26    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  27    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  28    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  29    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  30    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  31    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  32    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  33    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  34    POSSIBILITY OF SUCH DAMAGE.
  35*/
  36
  37:- module(term_to_json,
  38          [ term_to_json/3,                     % +Term, +Bindings, -Json
  39            term_to_json/2                      % +Term, -Json
  40          ]).
  41:- use_module(library(apply)).
  42:- use_module(library(error)).
  43
  44%!  term_to_json(+Term, +Bindings, -JsonTerm) is det.
  45%!  term_to_json(+Term, -JsonTerm) is det.
  46%
  47%   Convert any general Prolog term into   a JSON term. Prolog lists
  48%   are  treated  in  a  special  way.  Also,  JSON  terms  are  not
  49%   converted. Mapping:
  50%
  51%     * Variable: =|{"type":"var", "name":<string>}|=
  52%     * Atom: =|{"type":"atom", "value":<string>}|=
  53%     * Integer: =|{"type":"integer", "value":<integer>}|=
  54%     * Float: =|{"type":"float", "value":<float>}|=
  55%     * List: JSON array
  56%     * Dict: a JSON object. Values are processed recursively.
  57%       (the tag is ignored)
  58%     * json([Key=Value, ...]): a JSON object Values are processed
  59%       recursively.
  60%     * compound: =|{"type":"compound", "functor":<string>, "args":<array>}|=
  61%
  62%   @param  Bindings is a list of Name=Var terms for variables that
  63%           get their name from the environment.
  64
  65term_to_json(Term, JSON) :-
  66    term_to_json(Term, [], JSON).
  67term_to_json(Term, Bindings, JSON) :-
  68    findall(X,
  69            (   maplist(bind_var, Bindings),
  70                numbervars(Term, 0, _, [singletons(true)]),
  71                to_json(Term, X)
  72            ),
  73            [JSON]).
  74
  75bind_var(Name=Var) :-
  76    (   var(Var)
  77    ->  Var = '$VAR'(Name)
  78    ;   true
  79    ).
  80
  81to_json(Term, '_') :-
  82    var(Term),
  83    !.
  84to_json(@(Symbol), Symbol) :-                   % compatibility
  85    atom(Symbol),
  86    json_symbol(Symbol),
  87    !.
  88to_json(Term, Term) :-
  89    atom(Term),
  90    !.                          % interpreted as a string
  91to_json(Term, Term) :-
  92    string(Term),
  93    !.
  94to_json(Term, Value) :-
  95    integer(Term),
  96    !,
  97    (   Term >= -(2**31), Term < 2**31
  98    ->  Value = Term
  99    ;   atom_number(Value, Term)
 100    ).
 101to_json(Term, Term) :-
 102    float(Term),
 103    !.
 104to_json(Term, JsonList) :-
 105    is_list(Term),
 106    !,
 107    maplist(to_json, Term, JsonList).
 108to_json(json(Pairs0), Term) :-
 109    must_be(list, Pairs0),
 110    maplist(pair_value_to_json_ex, Pairs0, Pairs),
 111    dict_pairs(Term, json, Pairs).
 112to_json(Term0, Term) :-
 113    is_dict(Term0),
 114    !,
 115    dict_pairs(Term0, Tag, Pairs0),
 116    maplist(pair_value_to_json, Pairs0, Pairs),
 117    dict_pairs(Term, Tag, Pairs).
 118to_json('$VAR'(Name), VarName) :-
 119    !,
 120    format(string(VarName), '~W', ['$VAR'(Name), [numbervars(true)]]).
 121to_json(Term, json{functor:F, args:JsonArgs}) :-
 122    Term =.. [F|Args],
 123    maplist(to_json, Args, JsonArgs).
 124
 125json_symbol(null).
 126json_symbol(true).
 127json_symbol(false).
 128
 129pair_value_to_json(Key-Value0, Key-Value) :-
 130    to_json(Value0, Value).
 131
 132pair_value_to_json_ex(Key=Value0, Key-Value) :-
 133    (atom(Key) ; integer(Key)),
 134    !,
 135    to_json(Value0, Value).
 136pair_value_to_json_ex(Elem, _) :-
 137    domain_error(json_key_value, Elem).