-2
//code:630

//jsonpb, why int64 -> json is string. like 10-->"10"

//https://github.com/golang/protobuf/blob/master/jsonpb/jsonpb.go

// Default handling defers to the encoding/json library.
b, err := json.Marshal(v.Interface())
if err != nil {
    return err
}
needToQuote := string(b[0]) != `"` && (v.Kind() == reflect.Int64 || v.Kind() == reflect.Uint64)
if needToQuote {
    out.write(`"`)
}
out.write(string(b))
if needToQuote {
    out.write(`"`)
}

Question:

Why append "\'" around the value?

Rene Knop
  • 1,788
  • 3
  • 15
  • 27
zzhongcy
  • 17
  • 4

1 Answers1

2

Because way that integers are represented in javascript means that the maximum integer is (2 to the power of 53)-1 (see https://stackoverflow.com/a/307200/1153938)

The biggest int from an int64 is larger than that, so in order to protect from the case of large ints, the library does a string of digits instead

As javascript numbers are signed the same goes for large negative numbers

Vorsprung
  • 32,923
  • 5
  • 39
  • 63
  • 1
    This is an implementation detail and in no way enforced by the JSON spec. The reason @Vorsprung gives is probably one factor in order to unmarshal with Javascript. – abergmeier Jun 20 '19 at 13:13
  • https://github.com/grpc-ecosystem/grpc-gateway/issues/438#issuecomment-330739676 – cherrot Feb 02 '21 at 06:30