Can any one help me in storing the json output of personality insights API to csv using Python?

1k views Asked by At

I have deployed my personality insights service App in Bluemix and I could invoke post command to send the text. I want to save the output of a data to csv, i had gone through the API documentation of Personality API, however i could not understand where i am going wrong. Can any one help me in storing the output to csv file.

Here is the code i have used in Python.

#!/usr/bin/env python
# coding: utf-8

import requests
import json
import csv

response = requests.post("https://gateway.watsonplatform.net/personality-insights/api/v2/profile",
                         auth=("user-id", "password"),
                         headers={"content-type": "application/json", "Accept": "text/csv"},
                         data = "text to be analyzed"
                         )

jsonProfile = json.loads(response.text)

with open('test1234.csv', 'w') as f:
    for row in jsonProfile:
        f.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)

Please help me on this.

1

There are 1 answers

2
herchu On

You are already getting CSV data from the request, with the Accept: text/csv request header. All you need is to output this directly to a file, no need of using any library (Personality Insights has already formatted this for you!).

Here is a modified code that works:

response = requests.post("https://gateway.watsonplatform.net/personality-insights"+
                         "/api/v2/profile?headers=True",
     auth = ("userid", "password"),
     headers = {"content-type": "text/plain", "Accept": "text/csv"},
     data = "replace your text here"
     )
with open('personality-insights.csv', 'w') as f:
    print >> f, response.text

Also note the addition of the ?headers=True as query parameter in the URL: this will output the column names -- you will likely find this useful (If you are concatenating outputs of several API calls, then omit this parameter and just get the values as in your original example).