I am using the Google Natural Language API for project tag text with mood analysis. I want to save NL results as JSON. If Google receives a direct HTTP request, a JSON response is returned.
However, when using the provided Python libraries, an object is returned instead, and this object is not directly serializable JSON.
Here is an example of my code:
import os import sys import oauth2client.client from google.cloud.gapic.language.v1beta2 import enums, language_service_client from google.cloud.proto.language.v1beta2 import language_service_pb2 class LanguageReader:
Now, if you were to run:
sample_text="I love R&B music. Marvin Gaye is the best. 'What Going On' is one of my favorite songs. It was so sad when Marvin Gaye died." resp = LanguageReader(sample_text).results print resp
You'll get:
document_sentiment { magnitude: 2.40000009537 score: 0.40000000596 } language: "en" sentences { text { content: "I love R&B music." } sentiment { magnitude: 0.800000011921 score: 0.800000011921 } } sentences { text { content: "Marvin Gaye is the best." begin_offset: 18 } sentiment { magnitude: 0.800000011921 score: 0.800000011921 } } sentences { text { content: "\'What\ Going On\' is one of my favorite songs." begin_offset: 43 } sentiment { magnitude: 0.40000000596 score: 0.40000000596 } } sentences { text { content: "It was so sad when Marvin Gaye died." begin_offset: 90 } sentiment { magnitude: 0.20000000298 score: -0.20000000298 } }
This is not JSON. This is an instance of the google.cloud.proto.language.v1beta2.language_service_pb2.AnalyzeSentimentResponse object. And it does not have the __dict__ attribute attribute, so it is not serializable with json.dumps ().
How can I indicate that the response should be in JSON or serialize the object in JSON?
source share