Home > Software engineering >  unable to convert protobuf binary file to json in python - bytes' object has no attribute '
unable to convert protobuf binary file to json in python - bytes' object has no attribute '

Time:09-03

employees.proto file, compiles with protoc easily. and I import the resulting code into my own python code file as below.

syntax = "proto3";
package empList;

message Employee {
    int32 id = 1;
    string name = 2;
    float salary = 3;
}

message Employees {
    repeated Employee employees = 1;
}

Python file to add data and convert binary file to json.

import employees_pb2 as Test
from google.protobuf.json_format import MessageToDict
def main():
    emps = Test.Employees()
    obj1 = emps.employees.add()
    obj1.id = 10
    obj1.name = "Suresh"
    obj1.salary = 1000
    
    print(emps)
    with open("./serializedFile", "wb") as fd:
        t = emps.SerializeToString()
        fd.write(t)
        json_msg_string = MessageToDict(t, preserving_proto_field_name = True) 
        print("jsonSting : ", json_msg_string)
    empsRead = Test.Employees()
    with open("./serializedFile", "rb") as rfd:
        bstr = rfd.read()
        print(bstr)
        empsRead.ParseFromString(bstr)
    print(empsRead)

if __name__ == "__main__":
    main()
```
On running, I get the following traceback and I have been unable to understand the why I get the error of "AttributeError: 'bytes' object has no attribute 'DESCRIPTOR". Error is in the comment.

CodePudding user response:

Please try:

MessageToDict(emps, preserving_proto_field_name = True) 

MessageToDict takes the protobuf message (emps).

  • Related