在 Go 中,你可以使用内置的 encoding/json 包来处理 JSON 格式数据。该包提供了函数和类型,使你能够将 JSON 数据解析为 Go 对象(反序列化)或将 Go 对象转换为 JSON 数据(序列化)。
下面是一些常见的 JSON 处理操作:
反序列化(解析 JSON)
使用 json.Unmarshal 函数将 JSON 数据解析为 Go 对象。该函数接受一个包含 JSON 数据的字节切片和一个指向目标 Go 对象的指针,并将 JSON 数据映射到指定的 Go 对象上。
package mainimport ("encoding/json""fmt"
)type Person struct {Name string `json:"name"`Age int `json:"age"`
}func main() {jsonData := []byte(`{"name":"John", "age":30}`)var person Personerr := json.Unmarshal(jsonData, &person)if err != nil {fmt.Println("Error:", err)return}fmt.Println("Name:", person.Name)fmt.Println("Age:", person.Age)
}
序列化(将 Go 对象转换为 JSON)
使用 json.Marshal 函数将 Go 对象转换为 JSON 数据。该函数接受一个 Go 对象,并返回表示该对象的 JSON 字节切片。
package mainimport ("encoding/json""fmt"
)type Person struct {Name string `json:"name"`Age int `json:"age"`
}func main() {person := Person{Name: "John",Age: 30,}jsonData, err := json.Marshal(person)if err != nil {fmt.Println("Error:", err)return}fmt.Println(string(jsonData))
}
处理嵌套结构和数组
在 Go 中,你可以使用结构体嵌套和切片/数组来处理复杂的 JSON 数据结构。通过在结构体字段上添加 json 标签,可以指定 JSON 数据中的键名。
package mainimport ("encoding/json""fmt"
)type Address struct {City string `json:"city"`State string `json:"state"`
}type Person struct {Name string `json:"name"`Age int `json:"age"`Address []Address `json:"address"`
}func main() {jsonData := []byte(`{"name":"John", "age":30, "address":[{"city":"New York","state":"NY"},{"city":"San Francisco","state":"CA"}]}`)var person Personerr := json.Unmarshal(jsonData, &person)if err != nil {fmt.Println("Error:", err)return}fmt.Println("Name:", person.Name)fmt.Println("Age:", person.Age)fmt.Println("Address:", person.Address)
}
以上示例展示了如何在 Go 中处理 JSON 数据。你可以根据实际需求定义自己的数据结构,并使用 json 标签进行字段映射。
读取 JSON 文件
使用 os 和 io/ioutil 包来读取 JSON 文件的内容,并将其存储为字节切片。
使用 json.Unmarshal 函数将字节切片解析为 Go 对象。
package mainimport ("encoding/json""fmt""io/ioutil""os"
)type Person struct {Name string `json:"name"`Age int `json:"age"`
}func main() {file, err := os.Open("data.json")if err != nil {fmt.Println("Error:", err)return}defer file.Close()jsonData, err := ioutil.ReadAll(file)if err != nil {fmt.Println("Error:", err)return}var person Personerr = json.Unmarshal(jsonData, &person)if err != nil {fmt.Println("Error:", err)return}fmt.Println("Name:", person.Name)fmt.Println("Age:", person.Age)
}
在上述示例中,我们打开名为 data.json 的 JSON 文件,并将其内容读取为字节切片。然后,我们使用 json.Unmarshal 将字节切片解析为 Person 对象。
写入 JSON 文件
使用 os 和 io/ioutil 包来创建或打开要写入的 JSON 文件。
使用 json.MarshalIndent 函数将 Go 对象转换为带缩进的 JSON 字节切片。
使用 ioutil.WriteFile 函数将 JSON 字节切片写入 JSON 文件。
package mainimport ("encoding/json""fmt""io/ioutil"
)type Person struct {Name string `json:"name"`Age int `json:"age"`
}func main() {person := Person{Name: "John",Age: 30,}jsonData, err := json.MarshalIndent(person, "", " ")if err != nil {fmt.Println("Error:", err)return}err = ioutil.WriteFile("output.json", jsonData, 0644)if err != nil {fmt.Println("Error:", err)return}fmt.Println("JSON file created.")
}
在上述示例中,我们创建一个名为 output.json 的 JSON 文件,并将 Person 对象转换为带缩进的 JSON 字节切片。然后,我们使用 ioutil.WriteFile 将 JSON 字节切片写入文件。