在golang中,解析json是一項非常常見的任務。而當需要解析的json中有多維嵌套數據時,該如何進行解析呢?本文將介紹如何使用golang解析多維json。
首先,定義一個用于解析json的結構體。結構體中的字段名稱必須與json中的key名稱保持一致:
type person struct { Name string `json:"name"` Gender string `json:"gender"` Age int `json:"age"` Hobbies []string `json:"hobbies"` } type company struct { Name string `json:"name"` Location string `json:"location"` Employees []person `json:"employees"` }
假設我們有如下的json數據:
{ "name": "Google", "location": "Mountain View, CA", "employees": [ { "name": "John Doe", "gender": "male", "age": 30, "hobbies": ["reading", "jogging"] }, { "name": "Jane Smith", "gender": "female", "age": 25, "hobbies": ["swimming", "painting", "hiking"] } ] }
那么我們可以使用如下代碼進行解析:
jsonData := `{"name": "Google","location": "Mountain View, CA","employees": [{"name": "John Doe","gender": "male","age": 30,"hobbies": ["reading", "jogging"]},{"name": "Jane Smith","gender": "female","age": 25,"hobbies": ["swimming", "painting", "hiking"]}]}` var c company err := json.Unmarshal([]byte(jsonData), &c) if err != nil { panic(err) } fmt.Printf("Company name: %s\n", c.Name) fmt.Printf("Location: %s\n", c.Location) for _, e := range c.Employees { fmt.Printf("Employee name: %s\n", e.Name) fmt.Printf("Gender: %s\n", e.Gender) fmt.Printf("Age: %d\n", e.Age) fmt.Printf("Hobbies: %v\n\n", e.Hobbies) }
運行上述代碼將會輸出如下結果:
Company name: Google Location: Mountain View, CA Employee name: John Doe Gender: male Age: 30 Hobbies: [reading jogging] Employee name: Jane Smith Gender: female Age: 25 Hobbies: [swimming painting hiking]
如此便完成了golang解析多維json的操作。
下一篇html怎么增加代碼