Go语言的JSON处理

张开发
2026/4/16 20:17:05 15 分钟阅读

分享文章

Go语言的JSON处理
Go语言的JSON处理JSON基础JSONJavaScript Object Notation是一种轻量级的数据交换格式在Go语言中JSON处理由encoding/json包提供支持。基本使用JSON序列化将Go结构体转换为JSON字符串package main import ( encoding/json fmt ) type Person struct { Name string json:name Age int json:age City string json:city } func main() { person : Person{ Name: John, Age: 30, City: New York, } jsonData, err : json.Marshal(person) if err ! nil { fmt.Println(Error marshaling JSON:, err) return } fmt.Println(string(jsonData)) // {name:John,age:30,city:New York} }JSON反序列化将JSON字符串转换为Go结构体package main import ( encoding/json fmt ) type Person struct { Name string json:name Age int json:age City string json:city } func main() { jsonData : {name:John,age:30,city:New York} var person Person err : json.Unmarshal([]byte(jsonData), person) if err ! nil { fmt.Println(Error unmarshaling JSON:, err) return } fmt.Printf(Name: %s, Age: %d, City: %s\n, person.Name, person.Age, person.City) }结构体标签Go语言使用结构体标签来控制JSON序列化和反序列化的行为json:name指定JSON字段名json:name,omitempty当值为零值时不包含该字段json:-忽略该字段type Person struct { Name string json:name Age int json:age,omitempty City string json:city ZipCode int json:- // 忽略该字段 }高级用法处理嵌套结构体package main import ( encoding/json fmt ) type Address struct { City string json:city Country string json:country } type Person struct { Name string json:name Age int json:age Address Address json:address } func main() { person : Person{ Name: John, Age: 30, Address: Address{ City: New York, Country: USA, }, } jsonData, _ : json.Marshal(person) fmt.Println(string(jsonData)) // {name:John,age:30,address:{city:New York,country:USA}} }处理切片和映射package main import ( encoding/json fmt ) func main() { // 切片 fruits : []string{apple, banana, orange} jsonData, _ : json.Marshal(fruits) fmt.Println(string(jsonData)) // [apple,banana,orange] // 映射 person : map[string]interface{}{ name: John, age: 30, city: New York, } jsonData, _ json.Marshal(person) fmt.Println(string(jsonData)) // {age:30,city:New York,name:John} }自定义JSON序列化实现json.Marshaler接口来自定义序列化行为package main import ( encoding/json fmt time ) type CustomTime time.Time func (ct CustomTime) MarshalJSON() ([]byte, error) { return json.Marshal(time.Time(ct).Format(2006-01-02)) } type Event struct { Name string json:name EventTime CustomTime json:event_time } func main() { event : Event{ Name: Conference, EventTime: CustomTime(time.Now()), } jsonData, _ : json.Marshal(event) fmt.Println(string(jsonData)) // {name:Conference,event_time:2024-04-16} }示例完整的JSON处理package main import ( encoding/json fmt os ) type Config struct { Server ServerConfig json:server Database DBConfig json:database } type ServerConfig struct { Host string json:host Port int json:port } type DBConfig struct { DSN string json:dsn MaxOpenConns int json:max_open_conns MaxIdleConns int json:max_idle_conns } func main() { // 从文件读取JSON file, err : os.Open(config.json) if err ! nil { fmt.Println(Error opening config file:, err) return } defer file.Close() var config Config err json.NewDecoder(file).Decode(config) if err ! nil { fmt.Println(Error decoding JSON:, err) return } fmt.Printf(Server: %s:%d\n, config.Server.Host, config.Server.Port) fmt.Printf(Database DSN: %s\n, config.Database.DSN) // 修改配置并写回文件 config.Server.Port 8081 config.Database.MaxOpenConns 20 outputFile, err : os.Create(config.json) if err ! nil { fmt.Println(Error creating config file:, err) return } defer outputFile.Close() enconder : json.NewEncoder(outputFile) enconder.SetIndent(, ) // 美化输出 err enconder.Encode(config) if err ! nil { fmt.Println(Error encoding JSON:, err) return } fmt.Println(Config updated successfully) }性能优化使用json.Encoder和json.Decoder处理大文件避免一次性加载到内存对于频繁使用的JSON结构考虑使用代码生成工具如easyjson来提高性能减少不必要的字段和嵌套层次优化JSON结构总结Go语言的encoding/json包提供了强大的JSON处理能力支持序列化、反序列化、自定义序列化行为等功能。通过合理使用这些功能可以方便地处理JSON数据满足各种应用场景的需求。

更多文章