dialogflow / dialogflow-python-client

Python library for Dialogflow
Apache License 2.0
557 stars 195 forks source link

How do you convert google.cloud.dialogflow_v2.types.QueryResult to a python dictionary? #61

Closed ToddMorrill closed 6 years ago

ToddMorrill commented 6 years ago

I'm trying to convert a google.cloud.dialogflow_v2.types.QueryResult object to a simple python dictionary. I've got a fairly large custom payload coming through the webhook_payload attribute. Needless to say, when I simply call dict() on this object, I'm getting a lot of nested objects. I'm trying to avoid 1) writing a function to extract all the data from these nested objects, and 2) using the REST API.

Thanks for any help in advance.

response = session_client.detect_intent(session=session, query_input=query_input)
type(response.query_result.webhook_payload)
# google.cloud.dialogflow_v2.types.Struct

dict(response.query_result.webhook_payload)
# {u'hangouts': fields {
#   key: "cards"
#   value {
#     list_value {
#       values {
#         struct_value {
#           fields {
#             key: "header"
#             value {
#               struct_value {
#                 fields {
#                   key: "imageStyle"
#                   value {
#                     string_value: "IMAGE"
JainVikas commented 6 years ago

this is built using Struct protocols

In order to convert that you would need to use google proto buffer i.e google.protobuf I used the below code to do this.

import google.protobuf  as pf

pf.json_format.MessageToJson(response.query_result.fulfillment_messages[1].payload, including_default_value_fields=False)
igorpereirabr1 commented 5 years ago

Thanks!

kabirivan commented 2 years ago

I can revolve it, in this way:

Step 1: Import this lib

from google.protobuf.json_format import MessageToDict

Step 2: Send a request

agent = Agent( parent=parent, display_name=display_name, default_language_code="en", time_zone="America/Los_Angeles", )

request = SetAgentRequest( agent=agent, )

Step 3: Convert response to JSON [Look here, add ".pd"]

response = await agent_client.set_agent(request=request) new_response = MessageToDict(response._pb)

return IGetResponseBase(data=new_message)

Screen Shot 2022-08-18 at 19 19 01