Documentation
¶
Overview ¶
Package structpb contains generated types for google/protobuf/struct.proto.
The messages (i.e., Value, Struct, and ListValue) defined in struct.proto are used to represent arbitrary JSON. The Value message represents a JSON value, the Struct message represents a JSON object, and the ListValue message represents a JSON array. See https://json.org for more information.
The Value, Struct, and ListValue types have generated MarshalJSON and UnmarshalJSON methods such that they serialize JSON equivalent to what the messages themselves represent. Use of these types with the "google.golang.org/protobuf/encoding/protojson" package ensures that they will be serialized as their JSON equivalent.
Conversion to and from a Go interface ¶
The standard Go "encoding/json" package has functionality to serialize arbitrary types to a large degree. The Value.AsInterface, Struct.AsMap, and ListValue.AsSlice methods can convert the protobuf message representation into a form represented by any, map[string]any, and []any. This form can be used with other packages that operate on such data structures and also directly with the standard json package.
In order to convert the any, map[string]any, and []any forms back as Value, Struct, and ListValue messages, use the NewStruct, NewList, and NewValue constructor functions.
Example usage ¶
Consider the following example JSON object:
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 27,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
}
],
"children": [],
"spouse": null
}
To construct a Value message representing the above JSON object:
m, err := structpb.NewValue(map[string]any{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 27,
"address": map[string]any{
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100",
},
"phoneNumbers": []any{
map[string]any{
"type": "home",
"number": "212 555-1234",
},
map[string]any{
"type": "office",
"number": "646 555-4567",
},
},
"children": []any{},
"spouse": nil,
})
if err != nil {
... // handle error
}
... // make use of m as a *structpb.Value