JSON-LD + Hydra链接发现

Tom*_*icz 7 rest hateoas angularjs

我一直在考虑如何根据HATEOAS原则使用JSON-LD来驱动应用程序.

例如,我可以有一个简单的入口点对象,它定义了一个链接:

{
  "@context": {
    "users": { "@id": "http://example.com/onto#users", "@type": "@id" }
  },
  "@id": "http://example.com/api",
  "users": "http://example.com/users"
}
Run Code Online (Sandbox Code Playgroud)

并且#users谓词将被定义为Link使用Hydra:

{
  "@context": "http://www.w3.org/ns/hydra/context.jsonld",
  "@id": "http://example.com/onto#users",
  "@type": "Link"
}
Run Code Online (Sandbox Code Playgroud)

到目前为止一切都很好:应用程序获取资源,然后onto#users将解除引用资源以发现语义.

问题是实现者应该如何users从JSON-LD文档中发现属性的URI .当然,@context在我的示例中已明确定义,但该URI可以声明为QName:

"@context": {
  "onto": "http://example.com/onto#",
  "users": { "@id": "onto:users", "@type": "@id" }
}
Run Code Online (Sandbox Code Playgroud)

或者可以使用外部上下文或多个/嵌套上下文.

Javacript JSON-LD库中是否有一个函数,它会返回任何给定属性的绝对URI?或者有一种简单的方法可以找到它吗?无论@context结构如何,这种方式都可以发挥作用?就像是

var jsonLd = /* some odc */
var usersUri = jsonLd.uriOf('users');
expect(usersUri).toBe('http://example.com/onto#users');
Run Code Online (Sandbox Code Playgroud)

换句话说,我认为我正在寻找一个统一的API来阅读@context.

dlo*_*ley 4

以下是如何使用 JavaScript JSON-LD (jsonld.js) 库执行您所要求的操作:

var jsonld = require('jsonld');

var data = {
  "@context": {
    "onto": "http://example.com/onto#",
    "users": {"@id": "onto:users", "@type": "@id"}
  },
  "users": "http://example.com/users"
};

jsonld.processContext(null, [null, data['@context']], function(err, ctx) {
  if(err) {
    console.log('error', err);
    return;
  }
  var value = jsonld.getContextValue(ctx, 'users', '@id');
  console.log('users', value);
});
Run Code Online (Sandbox Code Playgroud)

然而,这是否是一个好主意值得怀疑。听起来也许您只想使用 jsonld.expand(),它将所有属性转换为完整的 URL。或者,您可以使用 jsonld.compact() 使用应用程序熟知的上下文来转换任何 JSON-LD 输入。