分享
golang encoding/json
rojas · · 4938 次点击 · · 开始浏览这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
1 package main 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 ) 8 9 type ColorGroup struct { 10 ID int 11 Name string 12 Colors []string 13 } 14 15 func main() { 16 17 //---------------Marshal 18 group := ColorGroup{ 19 ID: 1, 20 Name: "Reds", 21 Colors: []string{"Crimson", "Red", "Ruby", "Maroon"}, 22 } 23 b, err := json.Marshal(group) 24 if err != nil { 25 fmt.Println("error:", err) 26 } 27 //os.Stdout.Write(b) 28 fmt.Println(string(b[:])) 29 30 //---------------Unmarshal 31 var jsonBlob = []byte(`[ 32 {"ID":1,"Name":"Reds1","Colors":["Crimson","Red1","Ruby1","Maroon1"]}, 33 {"ID":2,"Name":"Reds2","Colors":["Crimson","Red2","Ruby2","Maroon2"]}, 34 {"ID":3,"Name":"Reds3","Colors":["Crimson","Red3","Ruby3","Maroon3"]} 35 ]`) 36 37 var animals []ColorGroup 38 error := json.Unmarshal(jsonBlob, &animals) 39 if error != nil { 40 fmt.Println("error:", error) 41 } 42 43 //fmt.Printf("%+v", animals) 44 //fmt.Println(animals) 45 for i, x := range animals { 46 fmt.Println(i, x) 47 48 } 49 //---------------Indent 50 dst := new(bytes.Buffer) 51 json.Indent(dst, jsonBlob, "##", "**") 52 fmt.Println(dst) 53 }
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信4938 次点击
上一篇:golang 命令行处理
1 回复 | 直到 2025年05月15日 08:41:23
暂无回复
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
1 package main 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 ) 8 9 type ColorGroup struct { 10 ID int 11 Name string 12 Colors []string 13 } 14 15 func main() { 16 17 //---------------Marshal 18 group := ColorGroup{ 19 ID: 1, 20 Name: "Reds", 21 Colors: []string{"Crimson", "Red", "Ruby", "Maroon"}, 22 } 23 b, err := json.Marshal(group) 24 if err != nil { 25 fmt.Println("error:", err) 26 } 27 //os.Stdout.Write(b) 28 fmt.Println(string(b[:])) 29 30 //---------------Unmarshal 31 var jsonBlob = []byte(`[ 32 {"ID":1,"Name":"Reds1","Colors":["Crimson","Red1","Ruby1","Maroon1"]}, 33 {"ID":2,"Name":"Reds2","Colors":["Crimson","Red2","Ruby2","Maroon2"]}, 34 {"ID":3,"Name":"Reds3","Colors":["Crimson","Red3","Ruby3","Maroon3"]} 35 ]`) 36 37 var animals []ColorGroup 38 error := json.Unmarshal(jsonBlob, &animals) 39 if error != nil { 40 fmt.Println("error:", error) 41 } 42 43 //fmt.Printf("%+v", animals) 44 //fmt.Println(animals) 45 for i, x := range animals { 46 fmt.Println(i, x) 47 48 } 49 //---------------Indent 50 dst := new(bytes.Buffer) 51 json.Indent(dst, jsonBlob, "##", "**") 52 fmt.Println(dst) 53 }