The Python Oracle

How to serialize default values in nested messages in Protobuf

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Realization

--

Chapters
00:00 Question
02:22 Accepted answer (Score 1)
03:17 Thank you

--

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

Question links:
[Protobuf doesn't serialize default values]: https://stackoverflow.com/questions/3102.../
https://github.com/protocolbuffers/proto...

Accepted answer links:
[Looping over Protocol Buffers attributes in Python]: https://stackoverflow.com/questions/2914...

--

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}}