4

A newbie to protobuff here. I am working on compressing a JSON file using protobuff. The problem is that this JSON file comes as a response from a webserver and contains certain fields whose name are random i.e. with each request posted to the server, the key names differ. For example consider the below JSON:

{
  "field1": [
       {
           "abc": "vala",
           "def": "valb",
           "ghi": "valc"
       }
   ],
  "field2": "val2",
  "field3": "val3"
}

In the above json, the field names "abc", "def", "ghi" can vary each time. Is there a way in protobuf so that I get field1's value completely (like a single string or anything else) without losing the random fields inside it?

PanDroid
  • 41
  • 1
  • 3

1 Answers1

2

I think you want "struct.proto", i.e.

syntax = "proto3";
import "google/protobuf/struct.proto";
message Foo {
     .google.protobuf.Struct field1 = 1;
     string field2 = 2;
     string field3 = 3;
}

or possibly (because of the array):

syntax = "proto3";
import "google/protobuf/struct.proto";
message Foo {
     repeated .google.protobuf.Struct field1 = 1;
     string field2 = 2;
     string field3 = 3;
}

However, I should emphasize that protobuf isn't well-suited for parsing arbitrary json; for that you should use a json library, not a protobuf library.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    Hey thanks for your response...but this does not work for me. Doesn't struct internally use map which need they "key" and "value" fields to be present? I was looking into a way to preserve unknown fields in serialization in proto2 or proto3..Could you tell me something about it? It could be of great help. – PanDroid Aug 17 '18 at 11:26