Go语言JSON 处理

本文涉及的产品
云解析 DNS,旗舰版 1个月
全局流量管理 GTM,标准版 1个月
公共DNS(含HTTPDNS解析),每月1000万次HTTP解析
简介: Go语言JSON 处理

JSON字符串解析到结构体


代码示例

type User struct {
 Name      string
 FansCount int64
}
// 如果反序列化的时候指定明确的结构体和变量类型
func TestJsonUnmarshal(t *testing.T) {
 const jsonStream = `
        {"name":"ethancai", "fansCount": 9223372036854775807}
    `
 var user User // 类型为User
 err := JsonUnmarshal(jsonStream, &user)
 if err != nil {
  fmt.Println("error:", err)
 }
 fmt.Printf("%+v \n", user)
}


解析Json数组到切片(数组)


type Person struct {
 Name string
 Age  int
}
type Family struct {
 Persons []Person
}
// 解析多维数组
var f Family
// 模拟传输的Json数据
familyJSON := `{"Persons": [{"Name":"Elinx","Age":26}, {"Name":"Twinkle","Age":21}] }`
fmt.Println("======================")
// 解析字符串为Json
json.Unmarshal([]byte(familyJSON), &f)

运行结果

=== RUN   TestJsonMash
======================
{[{Elinx 26 0001-01-01 00:00:00 +0000 UTC []} {Twinkle 21 0001-01-01 00:00:00 +0000 UTC []}]}
{"Persons":[{"Name":"Elinx","Age":26,"Birth":"0001-01-01T00:00:00Z","Children":null}
--- PASS: TestJsonMash (0.00s)
PASS

使用 struct tag 辅助构建 json

struct能被转换的字段都是首字母大写的字段,但如果想要在json中使用小写字母开头的key,可以使用struct的tag来辅助反射。

type Post struct {
 Id      int      `json:"ID"`
 Content string   `json:"content"`
 Author  string   `json:"author"`
 Label   []string `json:"label"`
}
func TestJsonMash1(t *testing.T){
 postp := &Post{
  2,
  "Hello World",
  "userB",
  []string{"linux", "shell"},
 }
 p, _ := json.MarshalIndent(postp, "", "\t")
 fmt.Println(string(p))
}

运行结果:

=== RUN   TestJsonMash1
{
 "ID": 2,
 "content": "Hello World",
 "author": "userB",
 "label": [
  "linux",
  "shell"
 ]
}
--- PASS: TestJsonMash1 (0.00s)
PASS

如何使用 tag


  • tag中标识的名称将称为json数据中key的值
  • tag可以设置为json:"-"来表示本字段不转换为json数据,即使这个字段名首字母大写
  • 如果想要json key的名称为字符"-",则可以特殊处理json:"-,",也就是加上一个逗号
  • 如果tag中带有,omitempty选项,那么如果这个字段的值为0值,即false、0、""、nil等,这个字段将不会转换到json中
  • 如果字段的类型为bool、string、int类、float类,而tag中又带有,string选项,那么这个字段的值将转换成json字符串

解析 Json 数据到结构已知 struct


{
    "id": 1,
    "content": "hello world",
    "author": {
        "id": 2,
        "name": "userA"
    },
    "published": true,
    "label": [],
    "nextPost": null,
    "comments": [{
            "id": 3,
            "content": "good post1",
            "author": "userB"
        },
        {
            "id": 4,
            "content": "good post2",
            "author": "userC"
        }
    ]
}

测试代码

type Post struct {
 ID        int64         `json:"id"`
 Content   string        `json:"content"`
 Author    Author        `json:"author"`
 Published bool          `json:"published"`
 Label     []string      `json:"label"`
 NextPost  *Post         `json:"nextPost"`
 Comments  []*Comment    `json:"comments"`
}
type Author struct {
 ID   int64  `json:"id"`
 Name string `json:"name"`
}
type Comment struct {
 ID      int64  `json:"id"`
 Content string `json:"content"`
 Author  string `json:"author"`
}
func TestJsonStruct(t *testing.T){
 jsonData :="{\n    \"id\": 1,\n    \"content\": \"hello world\",\n    \"author\": {\n        \"id\": 2,\n        \"name\": \"userA\"\n    },\n    \"published\": true,\n    \"label\": [],\n    \"nextPost\": null,\n    \"comments\": [{\n            \"id\": 3,\n            \"content\": \"good post1\",\n            \"author\": \"userB\"\n        },\n        {\n            \"id\": 4,\n            \"content\": \"good post2\",\n            \"author\": \"userC\"\n        }\n    ]\n}"
 var post Post
 // 解析json数据到post中
 err := json.Unmarshal([]byte(jsonData), &post)
 if err != nil {
  fmt.Println(err)
  return
 }
 fmt.Println(post)
 fmt.Println(post.Author, post.Content, post.Comments[0].Content,post.Comments[0].ID, post.Comments[0].Author )
}

运行结果

=== RUN   TestJsonStruct
{1 hello world {2 userA} true [] <nil> [0xc00016d1a0 0xc00016d1d0]}
{2 userA} hello world good post1 3 userB
--- PASS: TestJsonStruct (0.00s)
PASS
相关文章
|
1月前
|
JSON 人工智能 编译器
Go json 能否解码到一个 interface 类型的值
Go json 能否解码到一个 interface 类型的值
24 1
|
1月前
|
JSON Go 数据格式
Go - json.Unmarshal 遇到的小坑
Go - json.Unmarshal 遇到的小坑
43 9
|
22天前
|
JSON Go 数据格式
Go实现json字符串与各类struct相互转换
文章通过Go语言示例代码详细演示了如何实现JSON字符串与各类struct之间的相互转换,包括结构体对象生成JSON字符串和JSON字符串映射到struct对象的过程。
13 0
|
2月前
|
JSON Java Serverless
函数计算产品使用问题之如何使用Go SDK从HTTP上下文中提取JSON数据
函数计算产品作为一种事件驱动的全托管计算服务,让用户能够专注于业务逻辑的编写,而无需关心底层服务器的管理与运维。你可以有效地利用函数计算产品来支撑各类应用场景,从简单的数据处理到复杂的业务逻辑,实现快速、高效、低成本的云上部署与运维。以下是一些关于使用函数计算产品的合集和要点,帮助你更好地理解和应用这一服务。
|
2月前
|
JSON 前端开发 JavaScript
Go怎么解析不定JSON数据?
在Go中处理不确定结构的JSON数据,可以使用`map[string]interface{}`来解析,它能适应各种JSON键值对,但需要类型检查。另一种方法是使用`json.RawMessage`保存原始JSON,之后按需解析。此外,`json.Number`用于处理任意精度的数字。当JSON字段类型未知时,可以先解码到`interface{}`并做类型断言。第三方库如gjson和jsonparser提供更灵活的解析选项。
|
3月前
|
JSON Go 数据格式
go之json使用
go之json使用
|
4月前
|
JSON JavaScript 前端开发
Golang深入浅出之-Go语言JSON处理:编码与解码实战
【4月更文挑战第26天】本文探讨了Go语言中处理JSON的常见问题及解决策略。通过`json.Marshal`和`json.Unmarshal`进行编码和解码,同时指出结构体标签、时间处理、omitempty使用及数组/切片区别等易错点。建议正确使用结构体标签,自定义处理`time.Time`,明智选择omitempty,并理解数组与切片差异。文中提供基础示例及时间类型处理的实战代码,帮助读者掌握JSON操作。
87 1
Golang深入浅出之-Go语言JSON处理:编码与解码实战
|
4月前
|
JSON 编解码 Go
【Go语言专栏】Go语言中的JSON编码与解码
【4月更文挑战第30天】Go语言内置JSON编码解码支持,简化了数据交换。`json.Marshal`用于将Go结构体转换为JSON,如示例中`Person`结构体的编码。`json.Unmarshal`则将JSON数据反序列化到结构体,需传入结构体变量的地址。错误处理至关重要,特别是在处理大量数据时,要注意性能优化,如避免不必要的转换和重复操作。了解自定义编码解码和最佳实践能提升开发效率。掌握这些技能,有助于构建高效Go应用。
46 0
|
9月前
|
JSON Go 数据格式
go 变量与json相互转换
go 变量与json相互转换
57 1
|
10月前
|
JSON Linux 测试技术
go语言处理数据、基本通信以及环境配置 -- json,protobuf,grpc
go语言处理数据、基本通信以及环境配置 -- json,protobuf,grpc