3

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

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

4

1 回答 1

3

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

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

如果您要添加它@idtest.json它也适用于 RDFlib。

于 2015-07-28T21:39:50.167 回答