2

I have a Python API that receives data from mysql select query. The data looks like this:

| val | type | status |
|-----|------|--------|
|  90 |    1 |      a |

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

Here is my python 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)

with that, my client is receiving:

"[90, 1, "a"]"

Question:

is there a way for me to receive it as a proper JSON? like:

{'val': 90, 'type': 1 , : 'status': "a"}
3
  • you have to parse json string yourself on client side, e.g do json.loads if it's a python client. Commented Oct 19, 2016 at 13:48
  • Do the inverse of json.dumps(my_obj), by calling json.loads(my_string) Commented Oct 19, 2016 at 13:49
  • >>> x=[90, 1, "a"] >>> d={'val':x[0],'type':x[1],'status':x[2]} >>> json.dumps(d) '{"status": "a", "type": 1, "val": 90}' Commented Oct 19, 2016 at 13:54

1 Answer 1

1

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: Python - mysqlDB, sqlite result as dictionary is what you need.

Here is a link to the docs for MySQLdb: http://www.mikusa.com/python-mysql-docs/docs/MySQLdb.connections.html

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.

with self.connection.cursor(MySQLdb.cursors.DictCursor) as cursor:

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.