The Python Oracle

How to serialize default values in nested messages in Protobuf

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Sunrise at the Stream

--

Chapters
00:00 How To Serialize Default Values In Nested Messages In Protobuf
01:50 Accepted Answer Score 1
02:23 Thank you

--

Full question
https://stackoverflow.com/questions/5720...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #json #dictionary #protocolbuffers #protobuf3

#avk47



ACCEPTED ANSWER

Score 1


Based on the answer of Looping over Protocol Buffers attributes in Python I created a custom MessageToDict function:

def MessageToDict(message):
    message_dict = {}
    
    for descriptor in message.DESCRIPTOR.fields:
        key = descriptor.name
        value = getattr(message, descriptor.name)
        
        if descriptor.label == descriptor.LABEL_REPEATED:
            message_list = []
            
            for sub_message in value:
                if descriptor.type == descriptor.TYPE_MESSAGE:
                    message_list.append(MessageToDict(sub_message))
                else:
                    message_list.append(sub_message)
            
            message_dict[key] = message_list
        else:
            if descriptor.type == descriptor.TYPE_MESSAGE:
                message_dict[key] = MessageToDict(value)
            else:
                message_dict[key] = value
    
    return message_dict

Given the message read from the empty example.json this function returns:

{'subMessage': {'number': 0}}