简体   繁体   中英

How to iterate recursively over Protobuf Python message to find all field

This is how I did it, is there a native way to find all fields inside nested protobuf messages;

This is for a two layer nested message

for field in mes2.DESCRIPTOR.fields:
  if 'fields' in dir(field.message_type):
    for sub_field in field.message_type.fields:
      print(sub_field)  

You mean this?

message = [1, 7, {3: "tsdf", "y": (4, 7)}, [4, 8, 'w']]

def print_fields(message):
    if type(message) not in (list, tuple, dict, set):
        return
    for i in message:
        if type(i) in (list, tuple, dict, set):
            print_fields(i)
        else:
            print(i)

# -> 1, 7, 3, 'y', 4, 8, 'w'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM