Json 如何在Go中的嵌套对象数组中获取最深的对象
我有以下格式的JSON:Json 如何在Go中的嵌套对象数组中获取最深的对象,json,go,nested-object,Json,Go,Nested Object,我有以下格式的JSON: [ { "name": "Tree 1", "id": 1, "io_id": 12, "data": [ { "title": "tree 1 Cond 1", "id": 1,
[
{
"name": "Tree 1",
"id": 1,
"io_id": 12,
"data": [
{
"title": "tree 1 Cond 1",
"id": 1,
"childTriggerId": 10,
"children": [
{
"title": "tree 1 cond 1 Rule 1",
"id": 2,
"childTriggerId": 11
}, {
"title": "tree 1 cond 2",
"id": 2,
"childTriggerId": 11,
"children": [{
"title": "tree 1 cond 2 Rule 2",
"id": 2,
"childTriggerId": 11
}]
}, {
"title": "tree 1 Cond 3",
"id": 2,
"childTriggerId": 10,
"children": [{
"title": "tree 1 cond 3 Rule 1",
"id": 2,
"childTriggerId": 11
}]
}
]
}, {
"name": "Tree 2",
"io_id": 14,
"id": 2,
"data": [
{
"title": "tree 2 Cond 1",
"id": 2,
"childTriggerId": 10,
"children": [{
"title": "tree 2 Rule 1",
"id": 2,
"childTriggerId": 11
}]
}
]
}
]
}
]
我需要获取最深的对象并将它们传递给结构的切片。通过
最深的对象我指的是“children”键中的对象,它本身并没有
包含“children”键。这里的对象(或者说map[string]接口)I
期望获得的信息在标题中表示为“规则…”
请注意,不确定对象的嵌套方式。将数据传递给
结构对我来说不是问题,我不能只找出
识别最深的物体。以下是我的主要功能:
type Condition struct {
ID int64 `json:"id"`
Title string `json:"title"`
ChildTriggerId int64 `json:"childTriggerId"`
}
type Conditions []Condition
func main() {
var conditions Conditions
testJson, err := os.Open("tree-test.json")
if err != nil {
fmt.Println(err)
}
fmt.Println("Successfully opened trees.json")
defer testJson.Close()
byteValue, _ := ioutil.ReadAll(testJson)
jsonStruct := []interface{}{}
json.Unmarshal([]byte(byteValue), &jsonStruct)
// expect to find deepest objects here
}
是否有任何方法可以在不使用外部包的情况下完成此任务?
谢谢大家! 使用结构对JSON建模,并将其解组,然后您可以使用选择器自然地访问子对象。如果您不想对其建模,请使用中提供的帮助程序。我已尝试修复您的json,请检查是否正确。您能否澄清“最深对象”的含义?在您的示例中,您的具体意思是需要附加到“children”键的值,还是指任何对象,只要其与根的距离最大?@alessiosavi,谢谢,但该结构并不真正合适,而且,这是我从前端接收到的结构。@EliBendersky,我指的是附加到“children”键但其本身不包含“children”键的对象。谢谢注意,我会更新问题的