ffjson icon indicating copy to clipboard operation
ffjson copied to clipboard

struct marshal gives me extra space before the first field

Open csyangchen opened this issue 7 years ago • 2 comments

for some struct type, take this one for example:

type T struct {
    A string `json:"a"`
    B []int `json:"b,omitempty"`
}

ffjson MarshalJSON gives me output like this:

{ "a":"123"}
// expected:
{"a":"123"}

the generated code has:

...
buf.WriteString(`{ "a":`)
...

looking into ffjson code, I can see:

...
buf.Write("{ ")
...
buf.Rewind(1)
...

first write the space, then conditionally rewind.

However, the generated code fail on the aforementioned case.

csyangchen avatar Jan 19 '17 04:01 csyangchen

https://github.com/pquerna/ffjson/blob/master/inception/encoder.go#L110

Pretty sure it is needed though. Probably for this https://github.com/pquerna/ffjson/blob/master/inception/encoder.go#L117

klauspost avatar Jan 19 '17 09:01 klauspost

Maybe buf.Rewind(1) could become buf.RewindSuffix(",") where RewindSuffix(s) is a function that Rewinds the buffer by len(s) if the buffer ends with s. This way we wouldn't need the extra space in the first place.

CAFxX avatar Jun 06 '17 10:06 CAFxX