Skip to content

Instantly share code, notes, and snippets.

@tomcatzh
Last active August 29, 2015 14:17
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 tomcatzh/118e2f1811e8bba47f13 to your computer and use it in GitHub Desktop.
Save tomcatzh/118e2f1811e8bba47f13 to your computer and use it in GitHub Desktop.
How to using json parser in golang
package main
import (
"encoding/json"
"fmt"
"time"
)
// The custom time format for json
type MyTime time.Time
var myTimeFormat string = "2006-01-02 15:04:05 -0700 MST"
func (t MyTime) MarshalJSON() ([]byte, error) {
return []byte(time.Time(t).Format(`"` + myTimeFormat + `"`)), nil
}
func (t *MyTime) UnmarshalJSON(data []byte) (err error) {
ti, err := time.Parse(`"`+myTimeFormat+`"`, string(data))
*t = MyTime(ti)
return
}
func (t MyTime) String() string {
return time.Time(t).String()
}
type foobar struct {
// Simple type
Integer int `json:"integer"`
// The fieldname is case insensitive
String string
// Field not exists should be fine
Foobar int
// Time format, default RFC3339 format
CurrentTime time.Time `json:"current_time"`
// Can parse other format
LastTime MyTime `json:"last_time"`
// Closure should be fine
Closure struct {
Someting string `json:"something"`
Closure struct {
SomeNumber int `json:"some_number"`
} `json:"closure"`
} `json:"closure"`
}
func main() {
str := `{
"integer": 3,
"string": "Some String",
"current_time": "2015-03-13T16:14:45Z",
"last_time": "2015-03-13 16:14:45 +0000 UTC",
"closure": {
"something": "something foo bar",
"closure": {
"some_number": 123
}
}
}`
var f foobar
err := json.Unmarshal([]byte(str), &f)
fmt.Println(err)
fmt.Println(f)
newStr, err := json.Marshal(&f)
fmt.Println(string(newStr))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment