Search code examples
jsonjsonschemaobject-referenceobject-relationships

Referencing data in JSON


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

Solution

  • 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" }
            }
        }
    }