machazthegamer
machazthegamer

Reputation: 613

Python with google cloud language api Problem?

Using the google-cloud-language library for python how can I get the JSON returned from the following methods.

client.classify_text()
client.analyze_entity_sentiment()

the method response.serializetostring() seems to encode the result in a manner that can't be decoded in python. Not UTF-8 or unicode escape. I want to get the JSON so that I can dump it in mongodb.

Thanks in advance.

Upvotes: 1

Views: 242

Answers (1)

Dustin Ingram
Dustin Ingram

Reputation: 21520

You can use the google.protobuf.json_format.MessageToJson method to serialize a plain protobuf object to JSON. For example:

from google.cloud import language
from google.protobuf.json_format import MessageToJson

client = language.LanguageServiceClient()

document = language.types.Document(
    content='Mona said that jogging is very fun.',
    type='PLAIN_TEXT',
)

response = client.analyze_entity_sentiment(
    document=document,
    encoding_type='UTF32',
)

print(MessageToJson(response))

Prints:

{
  "entities": [
    {
      "name": "Mona",
      "type": "PERSON",
      "salience": 0.6080747842788696,
      "mentions": [
        {
          "text": {
            "content": "Mona"
          },
          "type": "PROPER",
          "sentiment": {
            "magnitude": 0.10000000149011612,
            "score": 0.10000000149011612
          }
        }
      ],
      "sentiment": {
        "magnitude": 0.10000000149011612,
        "score": 0.10000000149011612
      }
    },
    {
      "name": "jogging",
      "type": "OTHER",
      "salience": 0.39192524552345276,
      "mentions": [
        {
          "text": {
            "content": "jogging",
            "beginOffset": 15
          },
          "type": "COMMON",
          "sentiment": {
            "magnitude": 0.8999999761581421,
            "score": 0.8999999761581421
          }
        }
      ],
      "sentiment": {
        "magnitude": 0.8999999761581421,
        "score": 0.8999999761581421
      }
    }
  ],
  "language": "en"
}

Upvotes: 1

Related Questions