1

Disposition

Full illustrative code is available at this Gist.

Imagine we're describing a blog article in a JSON-LD document. In addition to a few properties of the article itself (its type and label), we want to add some semantic data for the purposes of that article. In this example, we define a Robot class and a Rover as its subclass, using @graph keyword.

{
    "@context": {
        "schema": "https://schema.org/",
        "blog": "https://blog.me/",
        "ex": "https://example.org/",
        "rdfs": "http://www.w3.org/2000/01/rdf-schema#"
    },
    "@id": "blog:JSONLD-and-named-graphs",
    "@type": "schema:blogPost",
    "rdfs:label": "JSON-LD and Named Graphs",
    "@graph": [
        {
            "@id": "ex:Robot",
            "@type": "rdfs:Class"
        },
        {
            "@id": "ex:Rover",
            "rdfs:subClassOf": {
                "@id": "ex:Robot"
            }
        }
    ]
}

Using Python rdflib, we want to import all of this into a named graph designated as https://myblog.net/rdf/ — like this:

    ...
    graph = ConjunctiveGraph()

    serialized_document = json.dumps(JSONLD_DOCUMENT)

    graph.parse(
        data=serialized_document,
        format='json-ld',
        # All the semantic data about my blog is stored in a particular
        # named graph.
        publicID='https://myblog.net/rdf/',
    )

Expected Result

All the data should be imported under named graph https://myblog.net/rdf/ based on the publicID argument.

Actual Result

In fact, we get two named graphs in our RDF dataset:

This is not a bug, this is what JSON-LD semantics prescribes. {"@id": "badoom", "@graph": {...}} means we've described a named @graph and provided its name as @id.

Question

Can we somehow override JSON-LD semantics and force RDFLib to import the whole of the input data into named graph specified by publicID argument?

Versions of the software:

Python 3.8.1
rdflib==5.0.0
rdflib-jsonld==0.5.0
PyLD==2.0.3
Anatoly Scherbakov
  • 1,672
  • 1
  • 13
  • 20

1 Answers1

1

It appears the appropriate tool for this job is @included keyword instead of @graph. See the JSON-LD 1.1 spec. That worked for me.

(P. S. I had to flatten the document before it worked with RDFLib; see the GitHub issue.)

Anatoly Scherbakov
  • 1,672
  • 1
  • 13
  • 20