filmov
tv
Go Golang JSON encode and decode struct, map, slice, array

Показать описание
Go Golang JSON encode and decode struct, map, slice, array
package main1
import (
"encoding/json"
"fmt"
)
/*A struct is a type which contains named fields.
Define new type named 'Person'*/
type Person struct {
Name string
Age int
Hobbies []string
}
func main1() {
/*initialize a struct.
Create an instance of type 'Person'*/
p1 := Person{"Sam", 20, []string{"cricket", "football"}}
/*p1 := &Person{name: "Sam", age: 20, hobbies: []string{"cricket", "football"}}*/
p1_json_ind, _ := json.MarshalIndent(p1, "", " ")
fmt.Println("==p1_json_ind==", string(p1_json_ind))
fmt.Printf("==p1==%#v \n", p1)
/*MAP*/
mapD := map[string]int{"apple": 5, "lettuce": 7}
mapB, _ := json.MarshalIndent(mapD, "", " ")
fmt.Println("==mapD==", string(mapB))
fmt.Printf("==map==%#v \n", mapD)
/*SLICE*/
slcD := []string{"apple", "peach", "pear"}
slcB, _ := json.MarshalIndent(slcD, "", " ")
fmt.Println("==slice==", string(slcB))
fmt.Printf("==slcD==%#v \n", slcD)
}
package main1
import (
"encoding/json"
"fmt"
)
/*A struct is a type which contains named fields.
Define new type named 'Person'*/
type Person struct {
Name string
Age int
Hobbies []string
}
func main1() {
/*initialize a struct.
Create an instance of type 'Person'*/
p1 := Person{"Sam", 20, []string{"cricket", "football"}}
/*p1 := &Person{name: "Sam", age: 20, hobbies: []string{"cricket", "football"}}*/
p1_json_ind, _ := json.MarshalIndent(p1, "", " ")
fmt.Println("==p1_json_ind==", string(p1_json_ind))
fmt.Printf("==p1==%#v \n", p1)
/*MAP*/
mapD := map[string]int{"apple": 5, "lettuce": 7}
mapB, _ := json.MarshalIndent(mapD, "", " ")
fmt.Println("==mapD==", string(mapB))
fmt.Printf("==map==%#v \n", mapD)
/*SLICE*/
slcD := []string{"apple", "peach", "pear"}
slcB, _ := json.MarshalIndent(slcD, "", " ")
fmt.Println("==slice==", string(slcB))
fmt.Printf("==slcD==%#v \n", slcD)
}