Go - JSON
encoding/json
包提供了对JSON格式文本的支持。
encoding/json
提供了4个函数
Encode()
Decode()
Marshal()
Unmarshal()
前两者操作单个对象,后两者操作多个对象。
Encode and Decode
JSON样例文件-readme.json
{
"Name":"Mihalis",
"Surname":"Tsoukalos",
"Tel":[
{"Mobile":true,"Number":"1234-567"},
{"Mobile":true,"Number":"1234-abcd"},
{"Mobile":false,"Number":"abcc-567"}
]
}
示例代码 - Read a JSON file
package main
import (
"encoding/json"
"fmt"
"os"
)
type Record struct {
Name string
Surname string
Tel []Telephone
}
type Telephone struct {
Mobile bool
Number string
}
func loadFromJSON(filename string, key interface{}) error {
in, err := os.Open(filename)
if err != nil {
return err
}
decodeJSON := json.NewDecoder(in)
err = decodeJSON.Decode(key)
if err != nil {
return err
}
in.Close()
return nil
}
func main() {
arguments := os.Args
if len(arguments) == 1 {
fmt.Println("Please provide a filename!")
return
}
filename := arguments[1]
var myRecord Record
err := loadFromJSON(filename, &myRecord)
if err == nil {
fmt.Println(myRecord)
} else {
fmt.Println(err)
}
}
示例代码 - Encode
package main
import (
"encoding/json"
"fmt"
"os"
)
type Record struct {
Name string
Surname string
Tel []Telephone
}
type Telephone struct {
Mobile bool
Number string
}
func saveToJSON(filename *os.File, key interface{}) {
encodeJSON := json.NewEncoder(filename)
err := encodeJSON.Encode(key)
if err != nil {
fmt.Println(err)
return
}
}
func main() {
myRecord := Record{
Name: "Mihalis",
Surname: "Tsoukalos",
Tel: []Telephone{Telephone{Mobile: true, Number: "1234- 567"},
Telephone{Mobile: true, Number: "1234-abcd"},
Telephone{Mobile: false, Number: "abcc-567"},
},
}
saveToJSON(os.Stdout, myRecord)
}
Marshal and Unmarshal
package main
import (
"encoding/json"
"fmt"
)
type Record struct {
Name string
Surname string
Tel []Telephone
}
type Telephone struct {
Mobile bool
Number string
}
func main() {
myRecord := Record{
Name: "Mihalis",
Surname: "Tsoukalos",
Tel: []Telephone{Telephone{Mobile: true, Number: "1234-567"},
Telephone{Mobile: true, Number: "1234-abcd"},
Telephone{Mobile: false, Number: "abcc-567"},
}}
rec, err := json.Marshal(&myRecord)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(rec))
var unRec Record
err1 := json.Unmarshal(rec, &unRec)
if err1 != nil {
fmt.Println(err1)
return
}
fmt.Println(unRec)
}
解析JSON
对于未结构化的JSON数据,Go会将其放到一个map中。
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
func main() {
arguments := os.Args
if len(arguments) == 1 {
fmt.Println("Please provide a filename!")
return
}
filename := arguments[1]
fileData, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Println(err)
return
}
var parsedData map[string]interface{}
json.Unmarshal([]byte(fileData), &parsedData)
for key, value := range parsedData {
fmt.Println("key:", key, "value:", value)
}
}
样例JSON
{
"Name": "John",
"Surname": "Doe",
"Age": 25,
"Parents": [
"Jim",
"Mary"
],
"Tel":[
{"Mobile":true,"Number":"1234-567"},
{"Mobile":true,"Number":"1234-abcd"},
{"Mobile":false,"Number":"abcc-567"}
]
}