0

I have a gRPC response in this format:

label {
  label {
    key: "blablafhidsahfoia"
  }
}
label {
  label {
    key: "asfhdkj"
    weight: 0.15829162299633026
  }
  label {
    key: "afdfafa"
    weight: 0.1708715856075287
  }
  label {
    key: "asdffd4e"
    weight: 0.13820932805538177
  }
  label {
    key: "afdffd"
    weight: 0.13021881878376007
  }
  label {
    key: "asdffd"
    weight: 0.08352510631084442
  }
  label {
    key: "dffdfdf"
    weight: 0.08115953952074051
  }
  label {
    key: "dffd"
    weight: 0.11294848471879959
  }
  label {
    key: "afdsdf"
    weight: 0.0846037045121193
  }
  label {
    key: "fasfer"
    weight: 0.040171828120946884
  }
}
label {
  label {
    key: "9fdsklj89fksd"
    weight: 1.0
  }
}
label {
  label {
    key: "random4rfsfd"
    weight: 1.0
  }
}
label {
  label {
    key: "jfkljf;sd"
  }
}

and I need to extract from each outer label, the inner label with the biggest weight or the only one if there is no weight. The response by itself is not iterable and I couldn't cast it to list or dictionary. I found that response has a function ListField() and the result is a list but only with one element which is a tuple like this:

response.ListFields()[0]
(<google.protobuf.pyext._message.FieldDescriptor object at 0x7ff786a76520>, [label {
  key: "blablafhidsahfoia"
}
, label {
  key: "asfhdkj"
  weight: 0.15829162299633026
}
label {
  key: "afdfafa"
  weight: 0.1708715856075287
}
label {
  key: "asdffd4e"
  weight: 0.13820932805538177
}
label {
  key: "afdffd"
  weight: 0.13021881878376007
}
label {
  key: "asdffd"
  weight: 0.08352510631084442
}
label {
  key: "dffdfdf"
  weight: 0.08115953952074051
}
label {
  key: "dffd"
  weight: 0.11294848471879959
}
label {
  key: "afdsdf"
  weight: 0.0846037045121193
}
label {
  key: "fasfer"
  weight: 0.040171828120946884
}
, label {
  key: "9fdsklj89fksd"
  weight: 1.0
}
, label {
  key: "random4rfsfd"
  weight: 1.0
}
, label {
  key: "jfkljf;sd"
}
])

so I can cast the second element in this tuple to string (which contains all of the data) and some string processing to get the values, is there a better way for doing this?


updates:

The response type is : class 'stat_test_pb2.StatResponse'

no746
  • 408
  • 6
  • 23

1 Answers1

1

Maybe convetion jo json would be good for you?

from google.protobuf.json_format import MessageToJson 
import json

json.loads(MessageToJson(response))
Ilia
  • 21
  • 1
  • 5
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 17 '22 at 11:01