Protobuf 사전 목록

Aug 18 2020

.proto에서 사전 목록을 정의하려고합니다.

내가 찾은 모든 예제는 단일 키, 값 쌍이있는 사전을 제공합니다.

message Pair {
   string key = 1;
   string value = 2;
}

message Dictionary {
   repeated Pair pairs = 1;
}

또는 다음과 같이 :

message Dictionary {
    message Pair {
        map<string, string> values = 1;
    }
    repeated Pair pairs = 1;
}

그러나 혼합 유형의 더 큰 사전을 어떻게 처리합니까?

{
'k1': 1,
'k2': 2,
'k3': 'three',
'k4': [1,2,3]
}

더 복잡하게하기 위해 혼합 값 사전을 정의한 후에는 이러한 사전 목록 인 메시지를 만들어야합니다. 사전이 중첩 된 또 다른 반복 메시지를 만드는 것만 큼 쉽습니다.

message DictList {
    repeated Dictionary dlist = 1;
}

답변

1 dmaixner Aug 18 2020 at 17:22

내가 생각 해낸 몇 가지 아이디어 :

  1. (모든 값 유형을 미리 알고있는 경우) oneof값 에 사용할 수 있어야합니다 (https://developers.google.com/protocol-buffers/docs/proto3#oneof). 문제를 해결할 수 있습니다. 예 :
message Value {
    oneof oneof_values {
        string svalue = 1;
        int ivalue = 2;
        ...
    }
}

message Pair {
   string key = 1;
   Value value = 2;
}

message Dictionary {
   repeated Pair pairs = 1;
}

그래도 내부 map또는 사용할 수 없습니다 .repeatedoneof

  1. 선택적 필드를 사용하고 모두 메시지 정의의 값으로 정의 할 수 있습니다. 그런 다음 실제로 사용하는 것만 설정하십시오.

  2. 래퍼 또는 알려진 유형을 사용할 수 있습니다. 예 Value:https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#google.protobuf.Value

편집하다

의 경우 다음 Value과 같이 사용할 수 있습니다.

map<string, google.protobuf.Value> dict = 1;
  1. 사용 struct(for_stack에서 제안한대로)은 여기에서 볼 수 있습니다. Python Dict에서 Protobuf Struct를 어떻게 생성합니까?