python - json-ld 别名不解析
问题描述
我正在尝试学习 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 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"
}
]
为了匹配您的压缩操场示例,您需要在上面添加上下文并使用 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"
}
推荐阅读
- swift - 如何将按钮与导航控制器的项目分离 - Swift
- vaadin - 如何在 vaadin 流网格中获取选定的行
- asp.net-core - 升级 TFM 后控制台应用程序不显示
- laravel - Laravel 用户有目标,用户必须针对目标进行销售,所以我想根据目标日期获取用户的销售数据
- php - 在 xml 文件中使用 PHP 代码回显某些内容
- php - 如何在多对多关系中更新数据透视表的数据
- c# - 在组合框中显示来自 DataGridviewImageColumn 的图像
- firebase - 如何将 Flutter Web 应用程序部署到托管在 Firebase 上的现有网站?
- jquery - 光滑的滑块在循环中无法正常工作
- python - RPi 模拟键盘,如何发送某些键码(左元)?