【问题标题】:Referencing data in JSON在 JSON 中引用数据
【发布时间】:2016-05-24 10:47:58
【问题描述】:

在 JSON 负载中,如何从一个地方引用另一个地方的数据?

用例:想象一下定义良好的可序列化实体 A (a1, a2, a3) 和 B (b1, b2, b3)。现在考虑一个期望以下内容的 HTTP 请求负载:

   {
     data : {
              "entityOne"   : Entity Representation of entity A,
              "entityTwo"   : Entity Representation of entity B
     },
     relationships : {
             "parenthood" : // Here I need to refer entityOne & entityTwo
                            // to express the notion of one being child of other
     }
   }

请告诉我您实现此引用的想法。

我考虑过的方法:

强制客户端针对有效负载中的每个实体发送一个临时参考 ID,并在关系中使用它们,如下所示

   {
     data : {
              "entityOne"   : { "id" : "temp1" -- other data for type A }
              "entityTwo"   : { "id" : "temp2" -- other data for type B }
     },
     relationships : {
             "parenthood" :  {
                                "parent" : "temp1",
                                "child"  : "temp2"
              }
     }
   }

【问题讨论】:

  • 你已经想到的方法有什么问题?
  • 强制客户端生成临时 ID 不是我想要的。想知道是否有标准的方式来引用 JSON 中的数据。我不确定,但 XPATH 允许在 XML 有效负载中使用类似的东西。已探索但找不到正确的指针

标签: json jsonschema object-reference object-relationships


【解决方案1】:

您可以使用 JSON 参考 https://datatracker.ietf.org/doc/html/draft-pbryan-zyp-json-ref-03

{
    "data" : {
        "entityOne": { ... }
        "entityTwo": { ... }
    },
    "relationships" : {
        "parenthood" :  {
            "parent" : { "$ref": "#/data/entityOne" },
            "child"  : { "$ref": "#/data/entityTwo" }
        }
    }
}

【讨论】:

  • 感谢 Jason 指出这一点。链接指向草稿。是否有任何库可以解析这些引用,或者我必须为它们编写自己的解析器并在 JSON 中导航
  • 这是一个草稿,但在 JSON Schema 中被广泛使用。我认为大多数实现都与 JSON Schema 验证器捆绑在一起,但我已经在 npm 上的 javascript 中看到了几个独立的实现。我不确定其他语言。如果需要,自己实现非常简单。
猜你喜欢
  • 1970-01-01
  • 2017-03-21
  • 2022-12-06
  • 2018-12-23
  • 2013-02-26
  • 2014-02-20
  • 2019-05-14
  • 2015-09-14
  • 2011-04-11
相关资源
最近更新 更多