Mercurial > repos > guerler > springsuite
comparison planemo/lib/python3.7/site-packages/rdflib/plugins/sparql/results/jsonresults.py @ 1:56ad4e20f292 draft
"planemo upload commit 6eee67778febed82ddd413c3ca40b3183a3898f1"
author | guerler |
---|---|
date | Fri, 31 Jul 2020 00:32:28 -0400 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
0:d30785e31577 | 1:56ad4e20f292 |
---|---|
1 from rdflib.query import ( | |
2 Result, ResultException, ResultSerializer, ResultParser) | |
3 from rdflib import Literal, URIRef, BNode, Variable | |
4 | |
5 from rdflib.py3compat import bytestype | |
6 | |
7 | |
8 from . import jsonlayer | |
9 | |
10 """A Serializer for SPARQL results in JSON: | |
11 | |
12 http://www.w3.org/TR/rdf-sparql-json-res/ | |
13 | |
14 Bits and pieces borrowed from: | |
15 http://projects.bigasterisk.com/sparqlhttp/ | |
16 | |
17 Authors: Drew Perttula, Gunnar Aastrand Grimnes | |
18 | |
19 """ | |
20 | |
21 | |
22 class JSONResultParser(ResultParser): | |
23 | |
24 def parse(self, source): | |
25 inp = source.read() | |
26 if isinstance(inp, bytestype): | |
27 inp = inp.decode('utf-8') | |
28 return JSONResult(jsonlayer.decode(inp)) | |
29 | |
30 | |
31 class JSONResultSerializer(ResultSerializer): | |
32 | |
33 def __init__(self, result): | |
34 ResultSerializer.__init__(self, result) | |
35 | |
36 def serialize(self, stream, encoding=None): | |
37 | |
38 res = {} | |
39 if self.result.type == 'ASK': | |
40 res["head"] = {} | |
41 res["boolean"] = self.result.askAnswer | |
42 else: | |
43 # select | |
44 res["results"] = {} | |
45 res["head"] = {} | |
46 res["head"]["vars"] = self.result.vars | |
47 res["results"]["bindings"] = [self._bindingToJSON( | |
48 x) for x in self.result.bindings] | |
49 | |
50 r = jsonlayer.encode(res) | |
51 if encoding is not None: | |
52 stream.write(r.encode(encoding)) | |
53 else: | |
54 stream.write(r) | |
55 | |
56 def _bindingToJSON(self, b): | |
57 res = {} | |
58 for var in b: | |
59 j = termToJSON(self, b[var]) | |
60 if j is not None: | |
61 res[var] = termToJSON(self, b[var]) | |
62 return res | |
63 | |
64 | |
65 class JSONResult(Result): | |
66 | |
67 def __init__(self, json): | |
68 self.json = json | |
69 if "boolean" in json: | |
70 type_ = 'ASK' | |
71 elif "results" in json: | |
72 type_ = 'SELECT' | |
73 else: | |
74 raise ResultException('No boolean or results in json!') | |
75 | |
76 Result.__init__(self, type_) | |
77 | |
78 if type_ == 'ASK': | |
79 self.askAnswer = bool(json['boolean']) | |
80 else: | |
81 self.bindings = self._get_bindings() | |
82 self.vars = [Variable(x) for x in json["head"]["vars"]] | |
83 | |
84 def _get_bindings(self): | |
85 ret = [] | |
86 for row in self.json['results']['bindings']: | |
87 outRow = {} | |
88 for k, v in list(row.items()): | |
89 outRow[Variable(k)] = parseJsonTerm(v) | |
90 ret.append(outRow) | |
91 return ret | |
92 | |
93 | |
94 def parseJsonTerm(d): | |
95 """rdflib object (Literal, URIRef, BNode) for the given json-format dict. | |
96 | |
97 input is like: | |
98 { 'type': 'uri', 'value': 'http://famegame.com/2006/01/username' } | |
99 { 'type': 'literal', 'value': 'drewp' } | |
100 """ | |
101 | |
102 t = d['type'] | |
103 if t == 'uri': | |
104 return URIRef(d['value']) | |
105 elif t == 'literal': | |
106 if 'xml:lang' in d: | |
107 return Literal(d['value'], lang=d['xml:lang']) | |
108 return Literal(d['value']) | |
109 elif t == 'typed-literal': | |
110 return Literal(d['value'], datatype=URIRef(d['datatype'])) | |
111 elif t == 'bnode': | |
112 return BNode(d['value']) | |
113 else: | |
114 raise NotImplementedError("json term type %r" % t) | |
115 | |
116 | |
117 def termToJSON(self, term): | |
118 if isinstance(term, URIRef): | |
119 return {'type': 'uri', 'value': str(term)} | |
120 elif isinstance(term, Literal): | |
121 if term.datatype is not None: | |
122 return {'type': 'typed-literal', | |
123 'value': str(term), | |
124 'datatype': str(term.datatype)} | |
125 else: | |
126 r = {'type': 'literal', | |
127 'value': str(term)} | |
128 if term.language is not None: | |
129 r['xml:lang'] = term.language | |
130 return r | |
131 | |
132 elif isinstance(term, BNode): | |
133 return {'type': 'bnode', 'value': str(term)} | |
134 elif term is None: | |
135 return None | |
136 else: | |
137 raise ResultException( | |
138 'Unknown term type: %s (%s)' % (term, type(term))) |