How to return JSON from Python REST API
<p>I have a Python API that receives data from mysql select query. The data looks like this:</p>

<pre><code>| val | type | status |
|-----|------|--------|
|  90 |    1 |      a |
</code></pre>

<p>That data was received well in python. Now I want to present that data as JSON to my REST client - how?</p>

<p>Here is my python code:</p>

<pre><code>def somefunction(self, by, identifier):
    # validate args
    procedure = 'mysproc' + str(by)

    try:
        with self.connection.cursor() as cursor:
            cursor.callproc(procedure,[str(identifier)])
            self.connection.commit()
            result = cursor.fetchone()

            print("+++ Result: " + str(result) + " +++")
    except:
        result = "Request Failed"
        raise
    finally:
        self.DestroyConnection()

    return json.dumps(result)
</code></pre>

<p>with that, my client is receiving:</p>

<pre><code>"[90, 1, "a"]"
</code></pre>

<p>Question:</p>

<p>is there a way for me to receive it as a proper JSON? like:</p>

<pre><code>{'val': 90, 'type': 1 , : 'status': "a"}
</code></pre>

<p>You will first need to get the mysql query to return a dict object instead of a list. If your library is MySQLdb then this answer: <a href="http://stackoverflow.com/questions/4147707/python-mysqldb-sqlite-result-as-dictionary">Python - mysqlDB, sqlite result as dictionary</a> is what you need.</p>

<p>Here is a link to the docs for MySQLdb: <a href="http://www.mikusa.com/python-mysql-docs/docs/MySQLdb.connections.html" rel="nofollow">http://www.mikusa.com/python-mysql-docs/docs/MySQLdb.connections.html</a></p>

<p>I think if you pass in the cursor class you want to use when you create your cursor the result of fetchone will be a dictionary. </p>

<pre><code>with self.connection.cursor(MySQLdb.cursors.DictCursor) as cursor:
</code></pre>

<p>Running json.dumps(result) on a dictionary will give the output you are looking for.</p>

python mysql json rest python-3.x