bugfix json_format.py (#16382)

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 3af2569265
PiperOrigin-RevId: 622156823
pull/16412/head
zhangzibao 8 months ago committed by Copybara-Service
parent 9da1b86c30
commit f6bcf9c78f
  1. 2
      python/google/protobuf/json_format.py

@ -303,7 +303,7 @@ class _Printer(object):
# Use base64 Data encoding for bytes # Use base64 Data encoding for bytes
return base64.b64encode(value).decode('utf-8') return base64.b64encode(value).decode('utf-8')
else: else:
return value return str(value)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL: elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
return bool(value) return bool(value)
elif field.cpp_type in _INT64_TYPES: elif field.cpp_type in _INT64_TYPES:

Loading…
Cancel
Save