protobuf.js icon indicating copy to clipboard operation
protobuf.js copied to clipboard

Parsing camelCase and snake_case JSON objects into protobuf.js messages

Open dimo414 opened this issue 11 months ago • 1 comments

Google's JSON parsing functions, such as C++'s JsonStringToMessage(), accept JSON keys as camelCase even if the backing field is snake_case.

By contrast, protobuf.js (AFAICT) only supports one format or the other, depending on how the .proto is initially parsed. This is WAI as discussed in issues like this one.

I am moving an operation from C++ to TypeScript, and therefore needing to parse a JSON object that may or may not contain snake_case fields using protobuf.js. This was previously not an issue (we can all agree it's not ideal) because C++'s parser supports both. However I cannot see a reasonable way to do the same with protobuf.js, because encode() and fromObject() only look for keys with the configured casing.

I am considering using camelcase-keys to force my JSON objects to camelCase before passing them to protobuf.js, but this is brittle (notably, it mangles keys that are actually map entries, which could only be detected by a protobuf-aware parser).

I'm wondering what my options are here. Is there a both-cases-compatible fromJSON() operation I've missed? Do I need to implement my own code that traverses the message structure and corrects appropriate keys? Or is this something that could be added to this library?

dimo414 avatar Aug 17 '23 20:08 dimo414

Just to add, the Protobuf spec indicates parsers should accept both casings.

dimo414 avatar Sep 05 '23 20:09 dimo414