protobuf.js
protobuf.js copied to clipboard
toJSON switch enum from int to string
a message include an enum value, when use toJSON func, the enum will be changed to a string ,however, this is not what i want.
same problem
I too am having this issue and usually expresses itself as invalid wire type 7 at offset x
Linking sacaw's issue with the one filed in Meshtastic:
https://github.com/meshtastic/Meshtastic-device/issues/685
Same issue. After toJSON()
, every values should be same as before when accessing, but it not.
Here's an example.
proto:
enum Type
{
eGoods = 1;
eService = 2;
}
message OrderItem
{
optional Type type = 1;
}
the instance of this message:
OrderItem {
type: 2,
}
Before toJSON()
, access the property type
of the instance and it returns 2
. But after toJSON()
, access the attribute type
and it returns 'eService'
.
It is a WRONG behavior and causes unexpected result at runtime.
@dcodeIO @alexander-fenster
toJSON
is a shorthand of toObject
:
https://github.com/protobufjs/protobuf.js/blob/da34f43ccd51ad97017e139f137521782f5ef119/src/message.js#L131-L137
https://github.com/protobufjs/protobuf.js/blob/da34f43ccd51ad97017e139f137521782f5ef119/src/message.js#L119-L137
but using util.toJSONOptions
. Unless there is a bug somewhere in this (please provide a reproduction), usage is either
- use
toObject
instead with the options needed - or - - modify
util.toJSONOptions
to change the behavior oftoJSON
globally
https://github.com/protobufjs/protobuf.js/blob/da34f43ccd51ad97017e139f137521782f5ef119/src/util/minimal.js#L378-L399
toJSON
is a shorthand oftoObject
:https://github.com/protobufjs/protobuf.js/blob/da34f43ccd51ad97017e139f137521782f5ef119/src/message.js#L131-L137
https://github.com/protobufjs/protobuf.js/blob/da34f43ccd51ad97017e139f137521782f5ef119/src/message.js#L119-L137
but using
util.toJSONOptions
. Unless there is a bug somewhere in this (please provide a reproduction), usage is either
- use
toObject
instead with the options needed - or -- modify
util.toJSONOptions
to change the behavior oftoJSON
globallyhttps://github.com/protobufjs/protobuf.js/blob/da34f43ccd51ad97017e139f137521782f5ef119/src/util/minimal.js#L378-L399
Thanks @dcodeIO, maybe it's what we need. Our case is sometimes to set the message instance to response like ctx.body = { orderItem }
, so it will call toJSON()
and we want the behavior is that enums don't convert to string key.
Is there a way to configure the toJSONOptions
globally without modifying the source code? We use the CLI to generate JS static modules to use.
Yes, this should be possible with protobuf.util.toJSONOptions = ...
or likewise.
Nice solution. thanks
Try this:
protobuf.util.toJSONOptions ={ longs: String, enums: Number, bytes: String, json: true }
{ longs: String, enums: Number, bytes: String, json: true }
this worked for my case...thanks!