Nested fields

We can also use a message as a type of another message. It is similar to a map data structure. It is analogous to nested JSON.

For example, take a look at the following JSON code:

{
"site": {
"url": "https://example.org",
"latency": "5ms",
"proxies": [
{"url": "https://example-proxy-1.org", "latency": "6ms"},
{"url": "https://example-proxy-2.org", "latency": "4ms"}
]
}
}

The preceding JSON contains information about a site that has a list of proxies. Each proxy is a map itself and contains details such asĀ url and latency.

How can we model the same thing in protobufs? We can do this using the nested messages, as shown in the following code:

message Site {
string url = 1;
int latency = 2;
repeated Proxy proxies = 3;
}

message Proxy {
string url = 1;
int latency = 2;
}

Here, we are nesting the Proxy type into Site. We will look at all of these field types soon. You can find more details about types here: https://developers.google.com/protocol-buffers/docs/proto.

In the next section, we'll learn about a protobuf compiler and how to use it.