Skip to content

Commit 1a20cd9

Browse files
authored
fix: dataset nquads serialization including RDFLib internal default graph identifier (#3262)
* fix: dataset nquads serialization including RDFLib internal default graph identifier * chore: remove json-ld code
1 parent 32b6b88 commit 1a20cd9

File tree

2 files changed

+43
-3
lines changed

2 files changed

+43
-3
lines changed

rdflib/plugins/serializers/nquads.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import warnings
44
from typing import IO, Any, Optional
55

6-
from rdflib.graph import ConjunctiveGraph, Graph
6+
from rdflib.graph import DATASET_DEFAULT_GRAPH_ID, ConjunctiveGraph, Graph
77
from rdflib.plugins.serializers.nt import _quoteLiteral
88
from rdflib.serializer import Serializer
99
from rdflib.term import Literal
@@ -45,17 +45,18 @@ def serialize(
4545

4646

4747
def _nq_row(triple, context):
48+
graph_name = context.n3() if context and context != DATASET_DEFAULT_GRAPH_ID else ""
4849
if isinstance(triple[2], Literal):
4950
return "%s %s %s %s .\n" % (
5051
triple[0].n3(),
5152
triple[1].n3(),
5253
_quoteLiteral(triple[2]),
53-
context.n3(),
54+
graph_name,
5455
)
5556
else:
5657
return "%s %s %s %s .\n" % (
5758
triple[0].n3(),
5859
triple[1].n3(),
5960
triple[2].n3(),
60-
context.n3(),
61+
graph_name,
6162
)
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
from rdflib import Dataset
2+
from rdflib.compare import isomorphic
3+
4+
5+
def test_nquads_default_graph():
6+
data = """
7+
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
8+
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
9+
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
10+
11+
{
12+
<urn:test> <http://www.w3.org/ns/prov#generatedAtTime> "2012-04-09"^^xsd:date .
13+
}
14+
15+
<urn:test> {
16+
<http://greggkellogg.net/foaf#me> a <http://xmlns.com/foaf/0.1/Person> ;
17+
<http://xmlns.com/foaf/0.1/knows> "http://manu.sporny.org/about#manu" ;
18+
<http://xmlns.com/foaf/0.1/name> "Gregg Kellogg" .
19+
20+
<http://manu.sporny.org/about#manu> a <http://xmlns.com/foaf/0.1/Person> ;
21+
<http://xmlns.com/foaf/0.1/knows> "http://greggkellogg.net/foaf#me" ;
22+
<http://xmlns.com/foaf/0.1/name> "Manu Sporny" .
23+
}
24+
"""
25+
26+
ds = Dataset()
27+
ds.parse(data=data, format="trig")
28+
output = ds.serialize(format="nquads")
29+
30+
# The internal RDFLib default graph identifier should not appear in the output.
31+
assert "<urn:x-rdflib:default>" not in output
32+
33+
# Ensure dataset round-trip still works.
34+
ds2 = Dataset()
35+
ds2.parse(data=output, format="nquads")
36+
for graph in ds.graphs():
37+
assert isomorphic(graph, ds2.graph(graph.identifier)), print(
38+
f"{graph.identifier} not isomorphic"
39+
)

0 commit comments

Comments
 (0)