Python(json):TypeError:期望的字符串或缓冲区

时间:2016-03-28 12:52:52

标签: 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)
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

2 个答案:

答案 0 :(得分:8)

>>> natural_sort(wrd) 'deMNorwWy' 需要一个字符串。执行此操作的正确方法是首先构造数据并使用json.loads(),它将为您提供json对象(实际上是一个字符串)。希望这会有所帮助。

答案 1 :(得分:6)

你必须改变两行,它才能正常工作。

  1. 删除此行:subjects = json.loads(result).read()
  2. 并且这样做:return json.dumps(result,indent = 4)
  3. 希望它会对你有所帮助。 :)