src/rdflib/plugins/sparql/results/jsonresults.py
1"""A Serializer for SPARQL results in JSON:
2
3http://www.w3.org/TR/rdf-sparql-json-res/
4
5Bits and pieces borrowed from:
6http://projects.bigasterisk.com/sparqlhttp/
7
8Authors: Drew Perttula, Gunnar Aastrand Grimnes
9"""
10
11from __future__ import annotations
12
13import json
14from typing import IO, Any, Dict, Mapping, MutableSequence, Optional
15
16from rdflib.query import Result, ResultException, ResultParser, ResultSerializer
17from rdflib.term import BNode, Identifier, Literal, URIRef, Variable
18
19try:
20 import orjson
21
22 _HAS_ORJSON = True
23except ImportError:
24 orjson = None # type: ignore[assignment, unused-ignore]
25 _HAS_ORJSON = False
26
27
28class JSONResultParser(ResultParser):
29 """Parses SPARQL JSON results into a Result object."""
30
31 # type error: Signature of "parse" incompatible with supertype "ResultParser"
32 def parse(self, source: IO, content_type: Optional[str] = None) -> Result: # type: ignore[override]
33 inp = source.read()
34 if _HAS_ORJSON:
35 try:
36 loaded = orjson.loads(inp)
37 except Exception as e:
38 raise ResultException(f"Failed to parse result: {e}")
39 else:
40 if isinstance(inp, bytes):
41 inp = inp.decode("utf-8")
42 loaded = json.loads(inp)
43 return JSONResult(loaded)
44
45
46class JSONResultSerializer(ResultSerializer):
47 """Serializes SPARQL results to JSON format."""
48
49 def __init__(self, result: Result):
50 ResultSerializer.__init__(self, result)
51
52 # type error: Signature of "serialize" incompatible with supertype "ResultSerializer"
53 def serialize(self, stream: IO, encoding: str = None) -> None: # type: ignore[override]
54 res: Dict[str, Any] = {}
55 if self.result.type == "ASK":
56 res["head"] = {}
57 res["boolean"] = self.result.askAnswer
58 else:
59 # select
60 res["results"] = {}
61 res["head"] = {}
62 res["head"]["vars"] = self.result.vars
63 res["results"]["bindings"] = [
64 self._bindingToJSON(x) for x in self.result.bindings
65 ]
66 if _HAS_ORJSON:
67 try:
68 r_bytes = orjson.dumps(res, option=orjson.OPT_NON_STR_KEYS)
69 except Exception as e:
70 raise ResultException(f"Failed to serialize result: {e}")
71 if encoding is not None:
72 # Note, orjson will always write utf-8 even if
73 # encoding is specified as something else.
74 try:
75 stream.write(r_bytes)
76 except (TypeError, ValueError):
77 stream.write(r_bytes.decode("utf-8"))
78 else:
79 stream.write(r_bytes.decode("utf-8"))
80 else:
81 r_str = json.dumps(res, allow_nan=False, ensure_ascii=False)
82 if encoding is not None:
83 try:
84 stream.write(r_str.encode(encoding))
85 except (TypeError, ValueError):
86 stream.write(r_str)
87 else:
88 stream.write(r_str)
89
90 def _bindingToJSON(self, b: Mapping[Variable, Identifier]) -> Dict[Variable, Any]:
91 res = {}
92 for var in b:
93 j = termToJSON(self, b[var])
94 if j is not None:
95 res[var] = termToJSON(self, b[var])
96 return res
97
98
99class JSONResult(Result):
100 def __init__(self, json: Dict[str, Any]):
101 self.json = json
102 if "boolean" in json:
103 type_ = "ASK"
104 elif "results" in json:
105 type_ = "SELECT"
106 else:
107 raise ResultException("No boolean or results in json!")
108
109 Result.__init__(self, type_)
110
111 if type_ == "ASK":
112 self.askAnswer = bool(json["boolean"])
113 else:
114 self.bindings = self._get_bindings()
115 self.vars = [Variable(x) for x in json["head"]["vars"]]
116
117 def _get_bindings(self) -> MutableSequence[Mapping[Variable, Identifier]]:
118 ret: MutableSequence[Mapping[Variable, Identifier]] = []
119 for row in self.json["results"]["bindings"]:
120 outRow: Dict[Variable, Identifier] = {}
121 for k, v in row.items():
122 outRow[Variable(k)] = parseJsonTerm(v)
123 ret.append(outRow)
124 return ret
125
126
127def parseJsonTerm(d: Dict[str, str]) -> Identifier:
128 """rdflib object (Literal, URIRef, BNode) for the given json-format dict.
129
130 input is like:
131
132 ```json
133 { 'type': 'uri', 'value': 'http://famegame.com/2006/01/username' }
134 { 'type': 'literal', 'value': 'drewp' }
135 ```
136 """
137
138 t = d["type"]
139 if t == "uri":
140 return URIRef(d["value"])
141 elif t == "literal":
142 return Literal(d["value"], datatype=d.get("datatype"), lang=d.get("xml:lang"))
143 elif t == "typed-literal":
144 return Literal(d["value"], datatype=URIRef(d["datatype"]))
145 elif t == "bnode":
146 return BNode(d["value"])
147 else:
148 raise NotImplementedError("json term type %r" % t)
149
150
151def termToJSON(
152 self: JSONResultSerializer, term: Optional[Identifier]
153) -> Optional[Dict[str, str]]:
154 if isinstance(term, URIRef):
155 return {"type": "uri", "value": str(term)}
156 elif isinstance(term, Literal):
157 r = {"type": "literal", "value": str(term)}
158
159 if term.datatype is not None:
160 r["datatype"] = str(term.datatype)
161 if term.language is not None:
162 r["xml:lang"] = term.language
163 return r
164
165 elif isinstance(term, BNode):
166 return {"type": "bnode", "value": str(term)}
167 elif term is None:
168 return None
169 else:
170 raise ResultException("Unknown term type: %s (%s)" % (term, type(term)))