首页 > 解决方案 > 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"
}

可以在这里看到: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 库时没有应用别名以及我做错了什么?

非常感谢

标签: pythonjsonschema.orgjson-ld

解决方案


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

推荐阅读