0

In a JSON payload, how does one refer to data at one place from another?

Use Case : Imagine well-defined serializable entities A (a1, a2, a3) and B (b1, b2, b3). Now consider an HTTP request payload that expects the following:

   {
     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
     }
   }

Please let me know your thoughts to achieve this referencing.

The approach I've considered:

Enforce client to send a temporary reference id against each entity in payload and use them in relationships as follows

   {
     data : {
              "entityOne"   : { "id" : "temp1" -- other data for type A }
              "entityTwo"   : { "id" : "temp2" -- other data for type B }
     },
     relationships : {
             "parenthood" :  {
                                "parent" : "temp1",
                                "child"  : "temp2"
              }
     }
   }
peak
  • 105,803
  • 17
  • 152
  • 177
DanglingPointer
  • 261
  • 1
  • 6
  • 19
  • 1
    What's wrong with the approach that you already thought? – user2004685 Feb 13 '16 at 06:48
  • Enforcing client to generate temporary id's is not I would like. Was wondering if there is standard way to reference data in JSON. I am not sure, but XPATH allowed something similar in XML payloads. Explored but couldn't find right pointers – DanglingPointer Feb 13 '16 at 07:01

1 Answers1

0

You could use JSON Reference 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" }
        }
    }
}
Community
  • 1
  • 1
Jason Desrosiers
  • 22,479
  • 5
  • 47
  • 53
  • Thanks Jason for pointing to this. The link points to a draft. Is there any library to parse these references or I have to write my own parser for them and navigate in JSON – DanglingPointer Feb 13 '16 at 07:31
  • It is a draft, but it is widely used in JSON Schema. I think most implementations out there are bundled with JSON Schema validators, but I've seen several standalone implementations in javascript on npm. I'm not sure about other languages. It's pretty simple to implement yourself if you need to. – Jason Desrosiers Feb 13 '16 at 08:03