go处理json

news/2024/10/22 2:54:48/

在 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 字节切片写入文件。


http://www.ppmy.cn/news/1423285.html

相关文章

AI大模型日报#0418:Stable Diffusion 3开放API、Meta新研究让AI Agent理解物理世界

导读: 欢迎阅读《AI大模型日报》,内容基于Python爬虫和LLM自动生成。目前采用“文心一言”生成了每条资讯的摘要。标题: 微软刚发布了VASA-1 这个人工智能可以让单张图像具有生动的说话和歌唱能力 摘要: 微软发布了VASA-1人工智能,它能使单…

MAC 终端命令

Command Shift . 显示隐藏文件夹 环境变量路径 ~/.zshrc ~/.bash_profile 每次打开都需要 source 安装Homebrew xcode安装 xcode-select --install brew安装 /bin/bash -c “$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)” 检查是否…

相机系列——透视投影:针孔相机模型

作者:木一 引言 上文我们提到,三维相机是对真实世界成像的模拟,为了让三维物体在计算机屏幕上呈现出来的图像符合人眼观察效果,通常采用透视投影方式模拟相机成像,为了简化计算,可以用针孔相机模型来描述…

安全开发实战(4)--whois与子域名爆破

目录 安全开发专栏 前言 whois查询 子域名 子域名爆破 1.4 whois查询 方式1: 方式2: 1.5 子域名查询 方式1:子域名爆破 1.5.1 One 1.5.2 Two 方式2:其他方式 总结 安全开发专栏 安全开发实战​​http://t.csdnimg.cn/25N7H 前言 whois查询 Whois 查询是一种用…

每日两题 / 142. 环形链表 II 146. LRU 缓存(LeetCode热题100)

142. 环形链表 II - 力扣(LeetCode) 用哈希记录走过的节点即可 /*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:Lis…

React搭建一个文章后台管理系统

1、项目准备 本篇文章讲解的是一个简单的文章后台管理系统,系统的功能很简单,如下:登录、退出;首页;内容(文章)管理:文章列表、发布文章、修改文章。 1)React官方脚手架:create-rea…

设计模式:备忘录模式

定义 备忘录模式(Memento Pattern)是一种行为设计模式,它允许在不暴露对象实现细节的前提下,捕获和外部化对象的内部状态,以便在将来某个时刻可以将该对象恢复到此状态。备忘录模式使用三个类类型来实现:发…

Flowable工作流引擎:Spring Boot集成指南

Flowable工作流引擎:Spring Boot集成指南 前言开始集成相关配置文件pom文件 前言 在快速变化的软件开发世界中,工作流管理成为了企业应用不可或缺的组成部分。无论是简化复杂业务流程、提升操作效率还是确保流程的一致性和透明性,一个强大的…