There isn't.
> The other aspect of this time format is when using Unmarshalling the
> json data to a type that is time.Time it errors.
>
> So currently after the json data has been unmarshalled I then re-parse
> the date string into time.Time types.
>
> Are there any of json.Unmarshal support these, or any time formats?
If you define your own time type and use that in the structures,
then you can give it an UnmarshalJSON method that can do
its own unmarshaling. That might be a good place to put the
stripping of .650 too.
See http://golang.org/pkg/json/#Unmarshaler
Russ
here's an example of that.
it was an interesting exercise - i wonder if there might be a place
for a couple of specialised functions to marshal and unmarshal JSON
strings, to avoid creating a bytes.Buffer and a json.Encoder/Decoder
each time. perhaps there's an easier way that i'm missing.
i thought it might be reasonable too to have a Nanoseconds
field in time.Time and a way of parsing/formatting sub-second time (999?)
package main
import (
"json"
"time"
"os"
"bytes"
"fmt"
)
const Fmt = "2006-01-02T15:04:05"
type jTime time.Time
func (jt *jTime) UnmarshalJSON(data []byte) os.Error {
b := bytes.NewBuffer(data)
dec := json.NewDecoder(b)
var s string
if err := dec.Decode(&s); err != nil {
return err
}
t, err := time.Parse(Fmt, s)
if err != nil {
return err
}
*jt = (jTime)(*t)
return nil
}
func (jt jTime) MarshalJSON() ([]byte, os.Error) {
var b bytes.Buffer
enc := json.NewEncoder(&b)
s := (*time.Time)(&jt).Format(Fmt)
enc.Encode(s)
return b.Bytes(), nil
}
type Foo struct {
T *jTime
I int
}
func main() {
var b bytes.Buffer
enc := json.NewEncoder(&b)
foo1 := Foo{(*jTime)(time.LocalTime()), 99}
if err := enc.Encode(foo1); err != nil {
fmt.Printf("err: %v\n", err)
}else{
fmt.Printf("foo1: %s\n", b.Bytes())
}
var foo2 Foo
dec := json.NewDecoder(&b)
if err := dec.Decode(&foo2); err != nil {
fmt.Printf("decode err: %v\n", err)
}else{
fmt.Printf("foo2: %v\n", foo2)
}
}
Russ
how did i miss that?!
const Fmt = "2006-01-02T15:04:05"
type jTime time.Time
func (jt *jTime) UnmarshalJSON(data []byte) os.Error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
t, err := time.Parse(Fmt, s)
if err != nil {
return err
}
*jt = (jTime)(*t)
return nil
}
func (jt jTime) MarshalJSON() ([]byte, os.Error) {
return json.Marshal((*time.Time)(&jt).Format(Fmt))
}
Russ