需求: 使用go语言将
struct
转为json
字符串,输出到文本中。要求:输出到文本的
json
字符串可阅读性好。
type User struct {
Name string
Age int8
}
func testMarshal() []byte {
users := []User{}
user1 := User{
Name: "zhangsan",
Age: 20,
}
user2 := User{
Name: "lisi",
Age: 23,
}
users = append(users, user1, user2)
marshal, err := json.Marshal(users)
if err != nil {
log.Fatal(err)
}
return marshal
}
func testWrite(data []byte) {
file, err := os.OpenFile("data.json", os.O_RDWR|os.O_CREATE, 0755)
if err != nil {
log.Fatal(err)
}
defer file.Close()
_, err = file.Write(data)
if err != nil {
log.Fatal(err)
}
}
func main(){
bytes := testMarshal()
testWrite(bytes)
}
// output:可以看见,输出的是json 字符串,但没有缩进格式,不是很方便阅读;但节省空间,可便于网络传输
// data.json--> [{"Name":"zhangsan","Age":20},{"Name":"lisi","Age":23}]
生成的json文件:
[{"Name":"zhangsan","Age":20},{"Name":"lisi","Age":23}]
type User struct {
Name string
Age int8
}
func testMarshalIndent() []byte {
users := []User{}
user1 := User{
Name: "zhangsan",
Age: 20,
}
user2 := User{
Name: "lisi",
Age: 23,
}
users = append(users, user1, user2)
marshal, err := json.MarshalIndent(users, "", "\t")
if err != nil {
log.Fatal(err)
}
return marshal
}
func testWrite(data []byte) {
file, err := os.OpenFile("data.json", os.O_RDWR|os.O_CREATE, 0755)
if err != nil {
log.Fatal(err)
}
defer file.Close()
_, err = file.Write(data)
if err != nil {
log.Fatal(err)
}
}
func main() {
bytes := testMarshalIndent()
testWrite(bytes)
}
生成的json文件
[
{
"Name": "zhangsan",
"Age": 20
},
{
"Name": "lisi",
"Age": 23
}
]
// 可阅读性比较好,但相应的空间资源回增加,不建议将此中格式用于网络传输
https://studygolang.com/pkgdoc