How to model {key:value, key:value, ...} object in the ProtoBuf

672 views
Skip to first unread message

MantasS

unread,
Nov 24, 2022, 12:06:25 PM11/24/22
to Protocol Buffers
I'm trying to model this JSON into ProtoBuff reply:
 "0xc02aaa39b223fe8d4a0e5c4f27ead9083c756cc2": "73185315951404654", "0x111111111117dc0aa78b770fa6a738034120c302": "90483392540197705773", "0xdac17f958d2ee523a2206206944597c13d831ec7": "2599292593",
 }

Tried to use map:

message Reply { map<string, string> balances = 1; }

but ended up with this error message: 
Object literal may only specify known properties, and '0xc02aaa39b223fe8d4a0e5c4f27ead9083c756cc2' does not exist in type 'Reply'.

Is there a way to return this type of JSON?


Josh Humphries

unread,
Nov 29, 2022, 1:59:17 PM11/29/22
to MantasS, Protocol Buffers
The map field didn't work because it would be an object inside the reply -- like so:
{
  "balances": {
    "somekey": "somevalue"
  }
}

To make the top-level object an arbitrary map, it would need to be a google.protobuf.Struct. This type is basically analogous to a JSON object with arbitrary keys/properties.

The downside to that type is that it is not type-safe: the values can be any type. So you'd need to do something special in the consuming code to check that all values are of an expected type (e.g. string).

----
Josh Humphries
jh...@bluegosling.com


--
You received this message because you are subscribed to the Google Groups "Protocol Buffers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to protobuf+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/protobuf/efabc47a-0c6d-4bd6-a152-0fc29a7a60c6n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages