1:- encoding(utf8).
36
37:- module(term_to_json,
38 [ term_to_json/3, 39 term_to_json/2 40 ]). 41:- use_module(library(apply)). 42:- use_module(library(error)).
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) :- 85 atom(Symbol),
86 json_symbol(Symbol),
87 !.
88to_json(Term, Term) :-
89 atom(Term),
90 !. 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)