Go语言学习: json 文件解析
用 go 语言解析 json 文件的笔记
JSON 是什么
JSON is short for JavaScript Object Notation
, a widely-used data interchange format. JSON is an extremely useful data format and is used almost everywhere today.
GO语言里的JSON支持
- bool for boolean data.
- string for strings.
- float64 for numbers.
- nil for null values.
序列化/反序列化
- json.Marshal: 将
go
的相关对象,转成json
字符串 - json.Unmarshal: 将
json
字符串转成go
对象
代码
Repo: https://github.com/aric-notes/golang-notes
./golang-notes/src/2022-08/2022-08-24
Marshaling Structs to JSON
将
go Book
数组,转化为json
字符串,未指定将大写的Key
转成小写的key
package main
import (
"encoding/json"
"fmt"
)
type Book struct {
Name string
Author string
}
func main() {
book := Book{"C++ programming language", "Bjarne Stroutsrup"}
// 将 go 对象转成 json 字符串
res, err := json.Marshal(book)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(res)) // {"Name":"C++ programming language","Author":"Bjarne Stroutsrup"}
}
Unmarshaling JSON in Go
将一个 JSON 字符串,转化为 Go 对象
package main
import (
"encoding/json"
"fmt"
)
type Game struct {
Name string
Rating float64
}
func main() {
codString := `{"Name": "Call of Duty", "Rating": 8.4}`
var cod Game
err := json.Unmarshal([]byte(codString), &cod)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%+v\n", cod) // {Name:Call of Duty Rating:8.4}
}
JSON arrays in Go Programming
JSON 数组的情况,需要自定义结构体,Array 的 Item
package main
import (
"encoding/json"
"fmt"
)
type Software struct {
Name string
Developer string
}
func main() {
softwaresJson := `[{"Name": "AutoCAD","Developer": "Autodesk"},{"Name": "Firefox","Developer": "Mozilla"},{"Name": "Chrome","Developer": "Google"}]`
var softwares []Software
err := json.Unmarshal([]byte(softwaresJson), &softwares)
if err != nil {
panic(err)
}
fmt.Println(softwares)
}
Slice to JSON in GoLang
切片,在 go 语言里的处理
package main
import (
"encoding/json"
"fmt"
)
type App struct {
Name string
}
func main() {
apps := []App{
{Name: "Google Play"},
{Name: "Evernote"},
{Name: "Buffer"},
}
appsJson, err := json.Marshal(apps)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(appsJson)) // [{"Name":"Google Play"},{"Name":"Evernote"},{"Name":"Buffer"}]
}
修改 json 的 key
type Book struct {
Name string `json:"title"`
Author Author `json:"author"`
}
任意类型
package main
import (
"encoding/json"
"fmt"
)
func main() {
unstructuredJson := `{"os": {"Windows": "Windows OS","Mac": "OSX","Linux": "Ubuntu"},"compilers": "gcc"}`
var result map[string]any
json.Unmarshal([]byte(unstructuredJson), &result)
fmt.Println(result["os"]) // map[Linux:Ubuntu Mac:OSX Windows:Windows OS]
}
实例: 读取一个 json 文件
users.json
{
"users": [
{
"name": "Elliot",
"type": "Reader",
"age": 23,
"social": {
"facebook": "https://facebook.com",
"twitter": "https://twitter.com"
}
},
{
"name": "Fraser",
"type": "Author",
"age": 17,
"social": {
"facebook": "https://facebook.com",
"twitter": "https://twitter.com"
}
}
]
}
main.go
- 读文件
- 定义 type struct
- 序列化/反序列化
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strconv"
)
// Users struct which contains
// an array of users
type Users struct {
Users []User `json:"users"`
}
// User struct which contains a name
// a type and a list of social links
type User struct {
Name string `json:"name"`
Type string `json:"type"`
Age int `json:"Age"`
Social Social `json:"social"`
}
// Social struct which contains a
// list of links
type Social struct {
Facebook string `json:"facebook"`
Twitter string `json:"twitter"`
}
func main() {
// Open our jsonFile
jsonFile, err := os.Open("users.json")
// if we os.Open returns an error then handle it
if err != nil {
fmt.Println(err)
}
fmt.Println("Successfully Opened users.json")
// defer the closing of our jsonFile so that we can parse it later on
defer jsonFile.Close()
// read our opened xmlFile as a byte array.
byteValue, _ := ioutil.ReadAll(jsonFile)
// we initialize our Users array
var users Users
// we unmarshal our byteArray which contains our
// jsonFile's content into 'users' which we defined above
json.Unmarshal(byteValue, &users)
// we iterate through every user within our users array and
// print out the user Type, their name, and their facebook url
// as just an example
for i := 0; i < len(users.Users); i++ {
fmt.Println("User Type: " + users.Users[i].Type)
fmt.Println("User Age: " + strconv.Itoa(users.Users[i].Age))
fmt.Println("User Name: " + users.Users[i].Name)
fmt.Println("Facebook Url: " + users.Users[i].Social.Facebook)
}
}