Skip to content

Instantly share code, notes, and snippets.

@hygull
Created December 9, 2016 00:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hygull/53792994c9f79e09d19ca5cf2bc7b853 to your computer and use it in GitHub Desktop.
Save hygull/53792994c9f79e09d19ca5cf2bc7b853 to your computer and use it in GitHub Desktop.
Marshalling JSON created by hygull - https://repl.it/EigQ/3
/*
{ "Date of creation" => "07 Dec 2016 (Started after 09:51 am)" }
{ "Aim of program" => "Marshalling JSON object" }
{ "Coded by" => "Rishikesh Agrawani" }
{ "Go version" => "1.7" }
*/
package main
import "fmt"
import "encoding/json"
type User struct {
Name string `json:"name"`
Age int8 `json:"age`
}
type Users struct {
Users []User
}
func main() {
users := []User{User{"Golang", 24}, User{"Python", 23}, User{"Rishikesh", 24}}
//We can also use json.Marshal(Users{users})........but it won't indent the JSON
usersSlice, err := json.MarshalIndent(Users{users}, "...", "\t")
if err != nil {
fmt.Println("Error...")
}
fmt.Println(string(usersSlice))
}
/* OUTPUT FOR ==> admins-MacBook-Pro-3:GoFiles admin$ go run slice_to_json.go
{
... "Users": [
... {
... "name": "Golang",
... "Age": 24
... },
... {
... "name": "Python",
... "Age": 23
... },
... {
... "name": "Rishikesh",
... "Age": 24
... }
... ]
...}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment