我想使用 expand
和 compact
jsonld.js 的方法库将来自各种来源的数据转换为通用格式进行处理。如果我获取源 JSON 文档,请添加 @context
给它,然后通过 expand
传递它方法我能够获得我需要的通用格式。
我无法找到解决方案的用例是需要合并多个值的情况。例如,schema.org 定义了一个 PostalAddress
为 streetAddress
设置一个字段,但许多系统将街道地址存储为单独的值(街道编号、街道名称、街道方向...)。要将传入数据转换为 schema.org 格式,我需要一种方法在我的 @context
中指明多个字段组成了 streetAddress
, 顺序正确。
压缩文件
{
"@context": {
"displaName": "http://schema.org/name",
"website": "http://schema.org/homepage",
"icon": "http://schema.org/image",
"streetNumber": "http://schema.org/streetAddress"
},
"displaName": "John Doe",
"website": "http://example.com/",
"icon": "http://example.com/images/test.png",
"streetNumber": "123",
"streetName": "Main St",
"streetDirection": "South"
}
扩展文档
{
"http://schema.org/name":[
{
"@value":"John Doe"
}
],
"http://schema.org/image":[
{
"@value":"http://example.com/images/test.png"
}
],
"http://schema.org/streetAddress":[
{
"@value":"123"
}
],
"http://schema.org/homepage":[
{
"@value":"http://example.com/"
}
]
}
我已经查看了所有我能找到的 JSON-LD 规范,但未能找到任何指示使用 @context
拆分或连接值的方法的内容。 .
有没有人知道一种方法可以将多个值以正确的顺序映射到一个上下文属性中,并可能在值之间添加空格。我还需要为相反的场景找到解决方案,在这种情况下,我需要以正确的顺序将一个字段拆分为多个值。
注意:即使我将所有三个属性都映射到 streetAddress
,这些值将全部包含在数组中,但不保证它们的顺序正确。
最佳答案
实现此目的的一种可能方法是为包含有序地址组件的地址使用单个数组字段(即 ["number", "direction", "name"]
)。然后在 @context
中,您可以使用 @container: @list
指定 address
,这将确保地址组件的顺序正确。
因此压缩后的文档将是:
{
"@context": {
"displaName": "http://schema.org/name",
"website": "http://schema.org/homepage",
"icon": "http://schema.org/image",
"address": {
"@id": "http://schema.org/streetAddress",
"@container": "@list"
}
},
"displaName": "John Doe",
"website": "http://example.com/",
"icon": "http://example.com/images/test.png",
"address": ["123", "South", "Main St"]
}
扩展后的是
{
"http://schema.org/streetAddress": [
{
"@list": [
{
"@value": "123"
},
{
"@value": "South"
},
{
"@value": "Main St"
}
]
}
],
"http://schema.org/name": [
{
"@value": "John Doe"
}
],
"http://schema.org/image": [
{
"@value": "http://example.com/images/test.png"
}
],
"http://schema.org/homepage": [
{
"@value": "http://example.com/"
}
]
}
关于javascript - 定义 JSON-LD @context 以连接/拆分值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33270064/