Ard*_*ant 3 python json web.py
我想从我的数据库中读取数据然后创建并返回一个json格式到我的python web服务器(web.py).但是下面的代码不起作用并给我这个错误:
TypeError:期望的字符串或缓冲区
在加载和加载之间切换也转储和转储(我无法理解为什么).如你了解我对python和json格式都是新手我会非常感谢你帮助我(看到很多帖子关于这个问题但仍然无法弄清楚该做什么)
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)
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
json.loads()期待一个字符串.正确的方法是先构建数据并使用json.dumps,这将为您提供一个json对象(实际上是一个字符串).希望这可以帮助.
你必须改变两行,它会工作正常.
希望它会对你有所帮助.:)