gpt4 book ai didi

python - json-ld 别名未解析

转载 作者:行者123 更新时间:2023-12-01 09:22:21 25 4
gpt4 key购买 nike

我正在尝试学习 json-ld,但在别名方面遇到了一些问题。

当我将 JSON-ld Playground 与以下上下文和文档一起使用时:

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

如此处所示:https://json-ld.org/playground/#startTab=tab-compacted&json-ld=%7B%22%40context%22%3A%7B%22url%22%3A%22%40id%22%2C%22a%22%3A%22%40type%22%2C%22name%22%3A%22http%3A%2F%2Fschema.org%2Fname%22%2C%22schema%22%3A%22http%3A%2F%2Fschema.org%2F%22%7D%2C%22url%22%3A%22http%3A%2F%2Fexample.com%2Fabout%23gregg%22%2C%22a%22%3A%22schema%3APerson%22%2C%22name%22%3A%22Gregg%20Kellogg%22%7D&context=%7B%22%40context%22%3A%22http%3A%2F%2Fschema.org%2F%22%7D

但是,当我使用带有以下代码的 Python pyld 库时:

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 库时没有应用别名以及我做错了什么吗?

非常感谢

最佳答案

这两个例子并不相同。 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"
}
]

为了匹配您的压缩 Playground 示例,您需要添加上述上下文并与 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"
}

关于python - json-ld 别名未解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50709437/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com