简体   繁体   中英

I'm trying to access some json data from a my sql server

Please be advised that I'm new to python. I tried to access data from a MySQL server with python. Thus far I have made the connection to the server and got the data but the trouble happens when I got to parse through the data. I got the error as follows.

TypeError: expected string or buffer

import MySQLdb
import json

if __name__ == "__main__":
    conn = create_con()
    cur = conn.cursor()
    cur.execute("select answer_option from question_answer")

    result = cur.fetchone()
    x = json.loads(result)

json loads -> returns an object from a string representing a json object.

json dumps -> returns a string representing a json object from an object.

so your json.loads is looking for a string representation. So you better do json.dumps and then do json.loads.

this should fix.

import MySQLdb
import json

    if __name__ == "__main__":
        conn = create_con()
        cur = conn.cursor()
        cur.execute("select answer_option from question_answer")

        result = cur.fetchone()
        x = json.dumps(result)
        x = json.loads(result)

TypeError: expected string or buffer clearly hints at the problem.

You could do print result to verify the type.

--

cursor.fetchone()

This method retrieves the next row of a query result set and returns a single sequence , or None if no more rows are available. Documentation reference here

==

json.loads(s)

This method deserialize a str or unicode instance containing a JSON document to a Python object using this conversion table. Refer this

--

So, I think perhaps you dont need json.loads... as result is already a python object.

By default, Cursor class returns rows as tuples.

    cur = conn.cursor()
    cur.excute("select answer_option from question_answer")
    result = cur.fetchone()

print(result) you get ("foo", )

You can do this to get your result

    x = result[0]

OR

include MySQLdb.cursors.DictCursor in your cursor to return rows as dictionaries. Then you can access them by name.

    cur = conn.cursor(MySQLdb.cursors.DictCursor)
    cur.excute("select answer_option from question_answer")
    result = cur.fetchone()

print(result) you get {"answer_option": "foo"}

You can access your result like this:

    x = result['answer_option']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM