亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在深度嵌套的 JSON 中將所有子 ID 與其父 ID 進行比較?

如何在深度嵌套的 JSON 中將所有子 ID 與其父 ID 進行比較?

Go
當年話下 2022-06-21 10:21:29
這是我需要驗證的 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 上運行它。


查看完整回答
反對 回復 2022-06-21
  • 1 回答
  • 0 關注
  • 148 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號