JSON-LD @id with IRI 导致空白节点

JSON-LD @id with IRI results in blank node

我在本地 Web 服务器上托管了一个 JSON 小文件,其中包含以下内容:

json_source = {"key1": "azerty", "key2": "qwerty", "key3": "lorem", "key4": "ipsum"}

使用 RDFLib 库,我正在解析 JSON,使用上下文添加一些语义并序列化为 N-Triples:

from rdflib import Graph

context ={"@id": "http://example.org/test",
          "@context": {"dct": "http://purl.org/dc/terms/",
                       "foaf": "http://xmlns.com/foaf/0.1/",
                       "key1": {"@id": "dct:language"},
                       "key2": {"@id": "dct:title"},
                       "key3": {"@id": "dct:title"},
                       "key4": {"@id": "foaf:name"}
           }
 }

g = Graph()
rdf = g.parse('http://localhost/test.json', format='json-ld', context=context)

print rdf.serialize(format="nt")

空白节点输出结果:

_:N6dc3aa6a68e34c36beade27af204cb6c <http://purl.org/dc/terms/language> "azerty" .
_:N6dc3aa6a68e34c36beade27af204cb6c <http://purl.org/dc/terms/title> "qwerty" .
_:N6dc3aa6a68e34c36beade27af204cb6c <http://xmlns.com/foaf/0.1/name> "ipsum" .
_:N6dc3aa6a68e34c36beade27af204cb6c <http://purl.org/dc/terms/title> "lorem" .

@id 不知何故没有解析为 http://example.org/test

但是,当将 JSON-LD 添加到 JSON-LD Playground 时:

{
   "@id": "http://example.org/test",
   "@context": {
   "dct": "http://purl.org/dc/terms/",
   "foaf": "http://xmlns.com/foaf/0.1/",
   "key1": {"@id": "dct:language"},
   "key2": {"@id": "dct:title"},
   "key3": {"@id": "dct:title"},
   "key4": {"@id": "foaf:name"}
},
"key1": "azerty",
"key2": "qwerty",
"key3": "lorem",
"key4": "ipsum"

}

...它解析为:

<http://example.org/test> <http://purl.org/dc/terms/language> "azerty" .
<http://example.org/test> <http://purl.org/dc/terms/title> "lorem" .
<http://example.org/test> <http://purl.org/dc/terms/title> "qwerty" .
<http://example.org/test> <http://xmlns.com/foaf/0.1/name> "ipsum" .

有人对如何解释差异有什么建议吗? 谢谢。

问题是你传递给rdflib的上下文不仅包含上下文(@context)而且还包含@id。然而,该方法忽略了除上下文之外的所有内容——顺便说一句,这是正确的。这在 JSON-LD 游乐场中起作用的原因是您将 @id 属性 添加到文档的 body,而不是上下文。当你传递给 playground 的文档打印成这样时就清楚了:

{
  "@context": {
    "dct": "http://purl.org/dc/terms/",
    "foaf": "http://xmlns.com/foaf/0.1/",
    "key1": { "@id": "dct:language" },
    "key2": { "@id": "dct:title" },
    "key3": { "@id": "dct:title" },
    "key4": { "@id": "foaf:name" }
  },
  "@id": "http://example.org/test",  <------------- part of the body, not the context
  "key1": "azerty",
  "key2": "qwerty",
  "key3": "lorem",
  "key4": "ipsum"
}

如果您将 @id 添加到 test.json,它也适用于 RDFlib。