I want to read data from my database then create and return a json format to my python web server (web.py).But following code doesn't work and gives me this error:
TypeError: expected string or buffer
Switched between loads and load also dumps and dump (Which i cant understand why).As you understand i'm very new to both python and json format i will be very thankful if you help me out(saw many post about this problem but still cant figure out what to do)
def ara_json(str):
web.header('Content-Type','application/json; charset=utf-8', unique=True)
cnx = mysql.connector.connect(user='arda', password='1', database='worddb')
cursor = cnx.cursor()
sqlq = "SELECT * FROM names WHERE name = '%s'" %str
cursor.execute(sqlq)
rows = cursor.fetchall()
result=[]
for row in rows:
d = dict()
d['name'] = row[0]
d['type'] = row[1]
result.append(d)
subjects = json.loads(result).read()
return json.dump(subjects , indent=4)
class json_isimbul:
def GET(self,isim):
web.header('Content-Type','application/json; charset=utf-8', unique=True)
isim = isim.lower()
return ara_json(isim)
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/application.py", line 239, in process
return self.handle()
File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/application.py", line 230, in handle
return self._delegate(fn, self.fvars, args)
File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/application.py", line 420, in _delegate
return handle_class(cls)
File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/application.py", line 396, in handle_class
return tocall(*args)
File "/home/arda/Downloads/arda/tmp/tornado/ps/sa2.py", line 98, in GET
return ara_json(isim)
File "/home/arda/Downloads/arda/tmp/tornado/ps/sa2.py", line 53, in ara_json
subjects = json.loads(result).read()
File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer
json.loads()
expects a string. The right way to do this is to first construct your data and use json.dumps
which will give you a json object(a string actually). Hope this helps.