go 分析与创建JSON

本文介绍了在Go语言中如何分析和创建JSON数据。对于分析JSON,文章提供了两种方法:使用`Unmarshal`函数和使用`Decoder`。使用Unmarshal时,需要创建结构体来容纳JSON数据,然后解码;使用Decoder则需要解码器逐个解码文件。创建JSON时,可以借助`Marshal`函数将结构体转换为JSON,或者使用编码器方法,先填充结构体,再将其编码到JSON文件中。
摘要由CSDN通过智能技术生成

JSON(JavaScript Object Notation)衍生与JavaScript语言的一种轻量级文本数据格式

1, 分析JSON

方法一: 使用Unmarshal函数

步骤: 1)创建一些用于包含JSON数据的结构

            2)通过json.Unmarshal函数, 把JSON数据解封到结构里面

例子:

要解析的文件 post.json

{
  "id" : 1,
  "content" : "Hello World!",
  "author" : {
    "id" : 2,
    "name" : "Sau Sheong"
  },
  "comments" : [
    { 
      "id" : 1, 
      "content" : "Have a great day!", 
      "author" : "Adam"
    },
    {
      "id" : 2, 
      "content" : "How are you today?", 
      "author" : "Betty"
    }
  ]
}

分析程序 json.go:

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
)

type Post struct {
	Id       int       `json:"id"`
	Content  string    `json:"content"`
	Author   Author    `json:"author"`
	Comments []Comment `json:"comments"`
}

type Author struct {
	Id   int    `json:"id"`
	Name string `json:"name"`
}

type Comment struct {
	Id      int    `json:"id"`
	Content string `json:"content"`
	Author  string `json:"author"`
}

func main() {
	jsonFile, err := os.Open("post.json")
	if err != nil {
		fmt.Println("Error opening JSON file:", err)
		return
	}
	defer jsonFile.Close()
	jsonData, err := ioutil.ReadAll(jsonFile)
	if err != nil {
		fmt.Println("Error reading JSON data:", err)
		return
	}

	fmt.Println(string(jsonData))
	var post Post
	json.Unmarshal(jsonData, &post)
	fmt.Println(post.Id)
	fmt.Println(post.Content)
	fmt.Println(post.Author.Id)
	fmt.Println(post.Author.Name)
	fmt.Println(post.Comments[0].Id)
	fmt.Println(post.Comments[0].Content)
	fmt.Println(post.Comments[0].Author)

}

运行  go run json.go

 

方法二: 使用Decoder

步骤:

1)创建出用于存储JSON数据的结构;

2) 创建出用于解码JSON数据的解码器;

3)遍历整个JSON文件并将数据解码至结构

package main

import (
	"encoding/json"
	"fmt"
	"io"
	"os"
)

type Post struct {
	Id       int       `json:"id"`
	Content  string    `json:"content"`
	Author   Author    `json:"author"`
	Comments []Comment `json:"comments"`
}

type Author struct {
	Id   int    `json:"id"`
	Name string `json:"name"`
}

type Comment struct {
	Id      int    `json:"id"`
	Content string `json:"content"`
	Author  string `json:"author"`
}

func main() {
	jsonFile, err := os.Open("post.json")
	if err != nil {
		fmt.Println("Error opening JSON file:", err)
		return
	}
	defer jsonFile.Close()
	//创建相应解码器
	decoder := json.NewDecoder(jsonFile)
	//遍历解码
	for {
		var post Post
		err := decoder.Decode(&post)
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Println("Error decoding JSON:", err)
			return
		}
		fmt.Println(post)
	}
}

  go run json.go  结果

{1 Hello World! {2 Sau Sheong} [{3 Have a great day! Adam} {4 How are you today}

2,创建JSON

方法一: 通过Marshal步骤

1)创建结构向其填充

2)把结构封装为JSON数据

创建程序为:

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
)

type Post struct {
	Id       int       `json:"id"`
	Content  string    `json:"content"`
	Author   Author    `json:"author"`
	Comments []Comment `json:"comments"`
}

type Author struct {
	Id   int    `json:"id"`
	Name string `json:"name"`
}

type Comment struct {
	Id      int    `json:"id"`
	Content string `json:"content"`
	Author  string `json:"author"`
}

func main() {

	post := Post{
		Id:      1,
		Content: "Hello World!",
		Author: Author{
			Id:   2,
			Name: "Sau Sheong",
		},
		Comments: []Comment{
			Comment{
				Id:      1,
				Content: "Have a great day!",
				Author:  "Adam",
			},
			Comment{
				Id:      2,
				Content: "How are you today?",
				Author:  "Betty",
			},
		},
	}

	output, err := json.MarshalIndent(&post, "", "\t\t")
	if err != nil {
		fmt.Println("Error marshalling to JSON:", err)
		return
	}
	err = ioutil.WriteFile("post.json", output, 0644)
	if err != nil {
		fmt.Println("Error writing JSON to file:", err)
		return
	}
}

生成的文件post.json

{
                "id": 1,
                "content": "Hello World!",
                "author": {
                                "id": 2,
                                "name": "Sau Sheong"
                },
                "comments": [
                                {
                                                "id": 1,
                                                "content": "Have a great day!",
                                                "author": "Adam"
                                },
                                {
                                                "id": 2,
                                                "content": "How are you today?",
                                                "author": "Betty"
                                }
                ]
}

方法二:编码器方式步骤:

1)创建结构并填充数据

2)创建出用于存储的JSON文件

3)创建出用于编码JSON数据的编码器

4)通过编码器把结构编码至JSON文件

package main

import (
	"encoding/json"
	"fmt"
	"io"
  "os"
)

type Post struct {
	Id       int       `json:"id"`
	Content  string    `json:"content"`
	Author   Author    `json:"author"`
	Comments []Comment `json:"comments"`
}

type Author struct {
	Id   int    `json:"id"`
	Name string `json:"name"`
}

type Comment struct {
	Id      int    `json:"id"`
	Content string `json:"content"`
	Author  string `json:"author"`
}

func main() {

	post := Post{
		Id:      1,
		Content: "Hello World!",
		Author: Author{
			Id:   2,
			Name: "Sau Sheong",
		},
		Comments: []Comment{
			Comment{
				Id:      1,
				Content: "Have a great day!",
				Author:  "Adam",
			},
			Comment{
				Id:      2,
				Content: "How are you today?",
				Author:  "Betty",
			},
		},
	}
	//创建JSON文件
	jsonFile, err := os.Create("post.json")
	if err != nil {
		fmt.Println("Error creating JSON file:", err)
		return
	}
	//创建编码器
	jsonWriter := io.Writer(jsonFile)
	encoder := json.NewEncoder(jsonWriter) 
	//结构编码至JSON文件 
	err = encoder.Encode(&post)
	if err != nil {
		fmt.Println("Error encoding JSON to file:", err)
		return
	}
}

结果

{"id":1,"content":"Hello World!","author":{"id":2,"name":"Sau Sheong"},"comments
":[{"id":1,"content":"Have a great day!","author":"Adam"},{"id":2,"content":"How
 are you today?","author":"Betty"}]}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值