Go語言中,處理JSON數據非常方便,一般使用標準庫中的“encoding/json”包。
首先,我們需要定義一個對應JSON格式的結構體,比如我們需要處理如下JSON數據:
{ "name": "張三", "age": 18, "hobby": ["reading", "music", "travelling"], "address": { "country": "China", "city": "Beijing" } }
我們可以定義一個結構體如下所示:
type Person struct { Name string `json:"name"` //標記json字段名為name Age int `json:"age"` //標記json字段名為age Hobby []string `json:"hobby"` //標記json字段名為hobby Address struct { //子結構體,處理嵌套的JSON數據 Country string `json:"country"` //標記json字段名為country City string `json:"city"` //標記json字段名為city } `json:"address"` }
在定義好結構體之后,我們就可以將JSON格式的數據解析到結構體中了:
import ( "encoding/json" "fmt" ) func main() { str := `{ "name": "張三", "age": 20, "hobby": ["reading", "music", "travelling"], "address": { "country": "China", "city": "Beijing" } }` var person Person err := json.Unmarshal([]byte(str), &person) if err != nil { fmt.Println("解析JSON數據失敗:", err) return } fmt.Println(person) }
運行該程序,將會輸出解析后的Person結構體,結果如下:
{Name:張三, Age:18, Hobby:[reading music travelling], Address:{Country:China, City:Beijing}}
同樣,我們也可以將一個結構體轉換成JSON格式的數據:
func main() { person := Person{ Name: "張三", Age: 18, Hobby: []string{"reading", "music", "travelling"}, Address: struct { Country string `json:"country"` City string `json:"city"` }{Country: "China", City: "Beijing"}, } jsonStr, err := json.Marshal(person) if err != nil { fmt.Println("將結構體轉換成JSON數據失敗:", err) return } fmt.Println(string(jsonStr)) }
運行該程序,將會輸出轉換后的JSON格式的數據,結果如下:
{"name":"張三","age":18,"hobby":["reading","music","travelling"],"address":{"country":"China","city":"Beijing"}}
以上就是Go語言中處理JSON數據的簡單介紹,希望對大家有所幫助!