1

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.
1
  • File "C:\protobuf\convert.py", line 30, in main json_msg_string = MessageToDict(t, preserving_proto_field_name = True) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\google\protobuf\json_format.py", line 168, in MessageToDict return printer._MessageToJsonObject(message) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\google\protobuf\json_format.py", line 203, in _MessageToJsonObject message_descriptor = message.DESCRIPTOR AttributeError: 'bytes' object has no attribute 'DESCRIPTOR' Commented Sep 2, 2022 at 22:10

1 Answer 1

1

Please try:

MessageToDict(emps, preserving_proto_field_name = True) 

MessageToDict takes the protobuf message (emps).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @DazWilkin it worked. Now I am kicking myself, why I did'nt think of that :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.