我正在努力学习json-ld,而且我的别名有一些问题。
当我在JSON-ld操场上使用以下上下文和文档时:
{
"@context": {
"url": "@id",
"a": "@type",
"name": "http://schema.org/name",
"schema": "http://schema.org/"
},
"url": "http://example.com/about#gregg",
"a": "schema:Person",
"name": "Gregg Kellogg"
}这一契约适当地规定:
{
"@context": "http://schema.org/",
"id": "http://example.com/about#gregg",
"type": "Person",
"name": "Gregg Kellogg"
}但是,当我使用Python库时,需要使用以下代码:
from pyld import jsonld
import json
doc = {
"url": "http://example.com/about#gregg",
"a": "schema:Person",
"name": "Gregg Kellogg"
}
context = {
"url": "@id",
"a": "@type",
"name": "http://schema.org/name",
"schema" : "http://schema.org/"
}
compacted = jsonld.compact(doc, context)
print(json.dumps(compacted, indent=2))只打印上下文而不打印文档:
{
"@context": {
"url": "@id",
"a": "@type",
"name": "http://schema.org/name",
"schema": "http://schema.org/"
}
}有人能解释为什么当我使用pyld库时没有应用别名,以及我做错了什么?
非常感谢
发布于 2018-06-08 23:23:06
这两个例子不一样。Python示例的问题是输入文档没有上下文。处理器首先扩展数据,并将导致未知的术语被删除。如果打印出扩展的数据,您可以看到这个问题:
expanded = jsonld.expand(doc)
print(json.dumps(expanded, indent=2))[]如果在上下文中添加,然后展开,您将看到正确的数据:
from pyld import jsonld
import json
context = {
"url": "@id",
"a": "@type",
"name": "http://schema.org/name",
"schema" : "http://schema.org/"
}
doc = {
"@context": context,
"url": "http://example.com/about#gregg",
"a": "schema:Person",
"name": "Gregg Kellogg"
}
expanded = jsonld.expand(doc)
print(json.dumps(expanded, indent=2))[
{
"@type": [
"http://schema.org/Person"
],
"http://schema.org/name": [
{
"@value": "Gregg Kellogg"
}
],
"@id": "http://example.com/about#gregg"
}
]为了匹配您的压缩操场示例,您需要像上面这样添加上下文,并使用schema.org上下文进行压缩:
...
compacted = jsonld.compact(doc, {"@context": "http://schema.org/"})
# or use the shortcut:
# compacted = jsonld.compact(doc, "http://schema.org/")
print(json.dumps(compacted, indent=2)){
"@context": "http://schema.org/",
"id": "http://example.com/about#gregg",
"type": "Person",
"name": "Gregg Kellogg"
}https://stackoverflow.com/questions/50709437
复制相似问题