From f6bcf9c78f99cc5466ba212a9cd73f45e27fd7f6 Mon Sep 17 00:00:00 2001 From: zhangzibao <1078763967@qq.com> Date: Fri, 5 Apr 2024 06:02:40 -0700 Subject: [PATCH] bugfix json_format.py (#16382) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In the _RegularMessageToJsonObject method, there is no str type conversion for non-bytes type values in the repeated content. This causes an exception in the MessageToJson method, as the jsons data does not allow for the occurrence of byte array type property values. BUG EG (contains proto and python code): ------------common.proto------------ message SafetyInfo{// repeated LoginDevice deviceList = 1; } message LoginDevice { optional string uuid = 1 [default = ""]; optional string deviceName = 2 [default = ""]; optional string deviceType = 3 [default = ""]; required uint32 lastTime = 4; } ------------test code(python)------------ from google.protobuf.json_format import MessageToJson import common_pb2 # generate by common.proto pb = common_pb2.SafetyInfo() pb_hex = "0a4e0a2039323833663530356533363332396338356638623866343832613561323061651211636d4a38426c307a4d20446576696365731a0f6950686f6e6520694f532031332e3720dc85a9b00628010a410a206233356161326632366236343966313536393466663761336263303434323163120950432dcdacd0cbb4ef1a0a57696e646f777320313020d5d2c6e705280010001800200028003001" pb.ParseFromString(bytes.fromhex(pb_hex)) print(pb) print(MessageToJson(pb)) Closes #16382 COPYBARA_INTEGRATE_REVIEW=https://github.com/protocolbuffers/protobuf/pull/16382 from zhangzibao:main 3af2569265598e9886ca3bbde25c77f1f717cde6 PiperOrigin-RevId: 622156823 --- python/google/protobuf/json_format.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/google/protobuf/json_format.py b/python/google/protobuf/json_format.py index 5ef75b9055..8a2e24975b 100644 --- a/python/google/protobuf/json_format.py +++ b/python/google/protobuf/json_format.py @@ -303,7 +303,7 @@ class _Printer(object): # Use base64 Data encoding for bytes return base64.b64encode(value).decode('utf-8') else: - return value + return str(value) elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL: return bool(value) elif field.cpp_type in _INT64_TYPES: