這是我需要驗證的 JSON 文檔。我必須檢查孩子中的所有 parent_id 是否正確。如果所有父子 ID 都是正確的,我將返回一個“有效”字符串。{ "id": 10, "children": [ { "id": 25, "parent_id": 10, "children": [ { "id": 131, "parent_id": 25, "children": null }, { "id": 33, "parent_id": 25, "children": [ { "id": 138, "parent_id": 33, "children": null }, { "id": 139, "parent_id": 33, "children": null }, { "id": 140, "parent_id": 33, "children": null }, { "id": 160, "parent_id": 33, "children": null }, { "id": 34, "parent_id": 33, "children": [ { "id": 26, "parent_id": 34, "children": null }, { "id": 64, "parent_id": 34, "children": null }, { "id": 65, "parent_id": 34, "children": null } ] }, { "id": 35, "parent_id": 33, "children": null }, { "id": 36, "parent_id": 33, "children": null }, { "id": 38, "parent_id": 33, "children": null }, { "id": 39, "parent_id": 33, "children": null }, { "id": 40, "parent_id": 33, "children": null },我從 API 中獲取值,但現在我很難編碼 Json 值
1 回答

森林海
TA貢獻2011條經驗 獲得超2個贊
定義與數據結構匹配的類型:
type node struct {
ID int `json:"id"`
ParentID int `json:"parent_id"`
MainID int `json:"main_id"`
Children []*node `json:"children"`
}
編寫一個遞歸函數來檢查數據:
func check(n *node) bool {
for _, c := range n.Children {
if c.ParentID != n.ID {
return false
}
if !check(c) {
return false
}
}
return true
}
將 JSON 解組為該類型的值。檢查結果。
var n node
err := json.Unmarshal(data, &n)
if err != nil {
log.Fatal(err)
}
fmt.Println(check(&n))
在 GoLang PlayGround 上運行它。
- 1 回答
- 0 關注
- 148 瀏覽
添加回答
舉報
0/150
提交
取消