35
36:- module(rdf_json,
37 [ graph_json/2, 38 properties_to_json/2, 39 rdf_object_to_json/2 40 ]). 41:- use_module(library(semweb/rdf_db)). 42:- use_module(library(semweb/rdf_describe)). 43:- use_module(library(semweb/rdf_bnode)). 44:- use_module(library(pairs)). 45:- use_module(library(apply)). 46:- use_module(library(assoc)). 47:- use_module(library(http/json)). 48:- use_module(library(http/json_convert)). 49:- use_module(library(http/http_json)).
63graph_json(Graph, json(JSON)) :-
64 bnode_vars(Graph, Graph1, BNodes),
65 bnode_ids(BNodes, 1),
66 map_list_to_pairs(arg(1), Graph1, Pairs),
67 keysort(Pairs, Pairs1),
68 group_pairs_by_key(Pairs1, SubjectKeyed),
69 maplist(json_description, SubjectKeyed, JSON).
70
71json_description(S-RDF, Key=json(JSON)) :-
72 uri_key(S, Key, _Type),
73 maplist(po, RDF, POList),
74 keysort(POList, POSorted),
75 group_pairs_by_key(POSorted, PList),
76 properties_to_json(PList, JSON).
77
78po(rdf(_,P,O), P-O).
79
80bnode_ids([], _).
81bnode_ids([bnode(N)|T], N) :-
82 N2 is N + 1,
83 bnode_ids(T, N2).
84
85uri_key(bnode(NodeID), Key, bnode) :-
86 !,
87 atom_concat('_:', NodeID, Key).
88uri_key(BNode, _, _) :-
89 rdf_is_bnode(BNode),
90 !,
91 type_error(rdf_resource, BNode).
92uri_key(URI, URI, uri).
98properties_to_json([], []) :- !.
99properties_to_json([P-Vs|T], [P=JSON|Rest]) :-
100 objects_to_json(Vs, JSON),
101 properties_to_json(T, Rest).
108objects_to_json([], []) :- !.
109objects_to_json([R|T], [json(JSON)|Vs]) :-
110 rdf_object_to_json(R, JSON),
111 objects_to_json(T, Vs).
122rdf_object_to_json(literal(Lit), Object) :-
123 !,
124 Object = [value=Txt, type=literal|Rest],
125 literal_to_json(Lit, Txt, Rest).
126rdf_object_to_json(URI, [value=Key, type=Type]) :-
127 uri_key(URI, Key, Type).
133literal_to_json(lang(Lang, Txt), Txt, [lang=Lang]) :- !.
134literal_to_json(type(Type, Txt), Txt, [datatype=Type]) :- !.
135literal_to_json(Txt, Txt, [])
JSON Representation for RDF graphs