带有IRI的JSON-LD @id导致空白节点

时间:2015-07-28 20:42:43

标签: python rdf json-ld rdflib blank-nodes

我在本地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" .

有人对如何解释差异有一些建议吗? 感谢。

1 个答案:

答案 0 :(得分:3)

问题是您传递给rdflib的上下文不仅包含上下文(@context),还包含@id。然而,该方法忽略了除了上下文之外的所有内容 - 这是正确的btw。这在JSON-LD游乐场中起作用的原因是您将@id属性添加到文档的 body ,而不是上下文。当你传递到操场上的文件被打印出来时,这一点就变得清晰了:

{
  "@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。