RDFLib / rdflib-jsonld

JSON-LD parser and serializer plugins for RDFLib
Other
282 stars 71 forks source link

Serializing with bnode graphs smushes them #69

Open jpmccu opened 5 years ago

jpmccu commented 5 years ago

Unlike trig, the JSON-LD serializer does not maintain distinct graphs when those graphs are identified using BNodes. The expectation should be to preserve the semantics as available, and keep the graphs distinct and identified (especially since the graph bnode itself can be used within a graph or another graph.

Here's an example in action:

>>> from rdflib import *
>>> g = ConjunctiveGraph()
>>> g1 = Graph(store=g.store, identifier=BNode())
>>> g1.add((URIRef("http://example.com/alice"),RDF.type,URIRef("http://example.com/Person")))
>>> g2 = Graph(store=g.store, identifier=BNode())
>>> g2.add((URIRef("http://example.com/bob"),RDF.type,URIRef("http://example.com/Person")))
>>> print(g.serialize(format="json-ld").decode('utf8'))
[
  {
    "@id": "http://example.com/bob",
    "@type": [
      "http://example.com/Person"
    ]
  },
  {
    "@id": "http://example.com/alice",
    "@type": [
      "http://example.com/Person"
    ]
  }
]
>>> g1.identifier
rdflib.term.BNode('N744ad2b3deb24f6b8c4a3798ca865a87')
>>> g2.identifier
rdflib.term.BNode('N3886a68ae1154b08ac7147347f5960d5')
>>> len(g1)
1
>>> len(g2)
1
>>> len(g)
2
>>> print(g.serialize(format="trig").decode('utf8'))

_:N3886a68ae1154b08ac7147347f5960d5 {
    <http://example.com/bob> a <http://example.com/Person> .
}

_:N744ad2b3deb24f6b8c4a3798ca865a87 {
    <http://example.com/alice> a <http://example.com/Person> .
}

I would expect the output of JSON-LD to be like this:

[
  {
    "@id" : "_:N3886a68ae1154b08ac7147347f5960d5",
    "@graph" : [
      {
        "@id": "http://example.com/bob",
        "@type": [
          "http://example.com/Person"
        ]
      }
    ]
  },
  {
    "@id" : "_:N744ad2b3deb24f6b8c4a3798ca865a87",
    "@graph" : [
      {
        "@id": "http://example.com/alice",
        "@type": [
          "http://example.com/Person"
        ]
      }
    ]
  }
]