danielgtaylor / danielgtaylor/python-betterproto

Cast "oneOf" value to a single value when converting to dict/JSON

Open
#388 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Python
Stars
1.8k
Forks
234
PR merge metrics
No merged PRs in 30d

Description

I am currently consuming metrics exposed by an OpenTelemetry agent, but when I try to convert the Protobuf metrics to JSON, the "oneOf" occurences are being translated to a dict instead of a single value. Is there any way to change this behavior to only display a single string value?

An example of what is happening:

The proto definitions (the original *.proto* files can be found [here](https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/common/v1/common.proto)):
```proto
syntax = "proto3";

message AnyValue {
oneof value {
string string_value = 1;
bool bool_value = 2;
int64 int_value = 3;
double double_value = 4;
ArrayValue array_value = 5;
KeyValueList kvlist_value = 6;
bytes bytes_value = 7;
}
}

message ArrayValue {
repeated AnyValue values = 1;
}

message KeyValueList {
repeated KeyValue values = 1;
}

message KeyValue {
string key = 1;
AnyValue value = 2;
}
```

The dataclasses generated:
```python
@dataclass
class KeyValue(betterproto.Message):
key: str = betterproto.string_field(1)
value: "AnyValue" = betterproto.message_field(2)

@dataclass
class AnyValue(betterproto.Message):
string_value: str = betterproto.string_field(1, group="value")
bool_value: bool = betterproto.bool_field(2, group="value")
int_value: int = betterproto.int64_field(3, group="value")
double_value: float = betterproto.double_field(4, group="value")
array_value: "ArrayValue" = betterproto.message_field(5, group="value")
kvlist_value: "KeyValueList" = betterproto.message_field(6, group="value")
bytes_value: bytes = betterproto.bytes_field(7, group="value")
```

The current conversion:
```json
{"key": "process.pid", "value": {"intValue": "275"}}
```

What I would like to have:
```json
{"key": "process.pid", "value": "275"}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.