This program demonstrates the encoding of Go data structures into JSON format. Let's go step-by-step:
-
Imports:
- The program imports the
fmtpackage for formatted I/O operations. - The
encoding/jsonpackage is imported to use the JSON encoding and decoding functionalities.
- The program imports the
-
Struct Definition:
type person struct { First string Last string Age int }
- A new
persontype is defined as a struct with three fields:First,Last, andAge.
- A new
-
Main Function:
p1 := person { First: "James", Last: "Bond", Age: 23, } p2 := person { First: "Shinshan", Last: "Kazama", Age: 5, }
- Two instances of the
personstruct,p1andp2, are created with different values.
sliceOfPeople := []person { p1, p2, }
- A slice of
personnamedsliceOfPeopleis created, containing bothp1andp2.
fmt.Println(sliceOfPeople)
- The slice
sliceOfPeopleis printed, which will show the two person structs in a slice format.
bs, err := json.Marshal(sliceOfPeople)
- The
json.Marshalfunction is called with thesliceOfPeopleslice. This function attempts to convert the slice into its JSON representation. If successful, the resulting JSON byte slice is stored inbs, anderrwill benil. If there's an error during the process, theerrvariable will capture that error.
if err != nil { fmt.Println(err) }
- If an error occurs during the JSON marshalling process, it will be printed.
fmt.Println(string(bs))
- The resulting JSON byte slice
bsis converted to a string and printed. This will show the JSON representation of thesliceOfPeopleslice.
- Two instances of the
Key Takeaway:
The program demonstrates how to convert a slice of structs into its corresponding JSON representation in Go. It's important to note that the field names of the struct (First, Last, and Age) are capitalized, ensuring they're exported and can be accessed by the json.Marshal function. If they were not capitalized, they would not be included in the JSON output.
- Run the following command
$ go run main.go
[{James Bond 23} {Shinshan Kazama 5}]
[{"First":"James","Last":"Bond","Age":23},{"First":"Shinshan","Last":"Kazama","Age":5}]