grpcprotoprotobufjs

Represent a protobuf map as a json


I'm using grpcc, which is based on protobuf.js, to test my grpc service APIs.

My .proto file:

message MyRequest {
    string userId = 1;
    map<string, string> params = 2;
}

I tried the following json body to send a request:

{userId : "my_user_id" , params: { name: "my_name"}}
{userId : "my_user_id" , params: [{"name":"my_name"}] }

But this gives the following error:

Error: Illegal value for Message.Field....MyRequest.params of type string: object (expected ProtoBuf.Map or raw object for map field)

How to correctly represent a protobuf map as a json?


Solution

  • The proper json body would be the following:

    { "userId": "my_user_id", "params": { "name": "my_name" } }

    What you've tried doing is an array of maps, which doesn't really mean anything in the context of protobuf. A map<string, string> is exactly the description of a json object, so more than one value would be represented the following way:

    { "params": { "key1": "value1", "key2": "value2" } }

    No need for an array.