1. 程式人生 > 實用技巧 >json解析與slice

json解析與slice

import (
 "encoding/json"
 "fmt"
)

type AutoGenerated struct {
 Age   int    `json:"age"`
 Name  string `json:"name"`
 Child []int  `json:"child"`
}

func main() {
 jsonStr1 := `{"age": 14,"name": "potter", "child":[1,2,3]}`
 a := AutoGenerated{}
 json.Unmarshal([]byte(jsonStr1), &a)
 aa := a.Child
 fmt.Println(aa)
 jsonStr2 := `{"age": 12,"name": "potter", "child":[3,4,5,7,8,9]}`
 json.Unmarshal([]byte(jsonStr2), &a)
 fmt.Println(aa)
}

第一感覺是,程式會輸出

[1 2 3]
[3 4 5 7 8 9]

然而正確的答案是

[1 2 3]
[3 4 5]

這道題關鍵的坑,其實是在 aa := a.Child ,變數 aa 實質是 一個長度為3,容量為4的切片;
然而,要將一個 JSON 陣列解碼到切片(slice)中,Unmarshal 將切片長度重置為零,然後將每個元素 append 到切片中。特殊情況,如果將一個空的 JSON 陣列解碼到一個切片中,Unmarshal 會用一個新的空切片替換該切片,由於是append,所以 a.child 切片的長度、容量也會跟隨發生改變。

在第二次列印 aa 時,由於其底層陣列 變為 【3 4 5 7 8 9】,且aa長度為3,所以會輸出【3 4 5】