我在postgres數據庫中有以下記錄。 parent_pk與父子關係中的pk相關。Postgres/JSON - 將父子關係轉換爲json
pk name type parent_pk --- ---- ---- --------- 1 hnumber101 house 0 2 hnumber201 house 0 101 dodge_charger vehicle 1 102 mustang vehicle 1 103 civic vehicle 2 301 john user 101 302 edward user 102 303 john user 102 304 john user 103 And I want to generate a json out of the above in the following format- [ { "id": 1, "name": "hnumber101", "type": "house" "child": [ { "id": 101, "name": "dodge charger", "type": "vehicle" "child": [{ "id": 301, "name": "john", "type": "user" }], }, { "id": 102, "name": "mustang", "type": "vehicle" "child": [{ "id": 303, "name": "john", "type": "user" }, { "id": 302, "name": "edward", "type": "user" }], }], }, { "id": 2, "name": "hnumber201", "type": "house" "child": [ { "id": 103, "name": "civic", "type": "vehicle" "child": [{ "id": 304, "name": "john", "type": "user" }], }], }]
我一直在使用WITH遞歸查詢的嘗試,但得到的條目列表,然後我必須做大量的循環周圍的/在我的Java代碼中的哈希映射來獲取父裏面那個孩子塊。 什麼是最有效的方法來做到這一點?
9.2中的JSON支持非常有限。 'row_to_json'構造函數不支持匿名行,沒有'scalar_to_json'或'json_escape'將單個值包裝爲JSON,並且沒有聚合或合併/附加函數。這使得建立與行類型不相對應的值非常困難:-( – 2012-08-09 23:35:10
您是否有將JSON文件加載到數據庫表中的代碼,保存ID和parentID? – 2015-12-12 18:16:55