2016-02-13 59 views
0

在JSON有效負載中,如何引用另一個地方的數據?用例:想象一下定義良好的可串行實體A(a1,a2,a3)和B(b1,b2,b3)。現在認爲有下面的一個HTTP請求負載:在JSON中引用數據

{ 
    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" 
       } 
    } 
    } 
+1

您認爲的方法有什麼問題? – user2004685

+0

強制客戶端生成臨時ID是不是我想要的。想知道是否有標準的方式來引用JSON數據。我不確定,但XPATH允許在XML有效載荷中使用類似的東西。探討,但無法找到正確的指針 – DanglingPointer

回答

0

你可以使用JSON參考https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03

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

謝謝傑森指出這一點。鏈接指向草稿。是否有任何庫來解析這些引用,或者我必須爲它們編寫我自己的解析器並以JSON導航 – DanglingPointer

+0

這是一個草稿,但它在JSON模式中被廣泛使用。我認爲大多數實現都與JSON Schema驗證器捆綁在一起,但我在npm上看到了幾個獨立的javascript實現。我不確定其他語言。如果需要,實現自己很簡單。 – Jason