python (JSON): TypeError: expected string or buffer

标签 python json web.py

我想从我的数据库中读取数据,然后创建一个 json 格式并将其返回到我的 python 网络服务器 (web.py)。但是下面的代码不起作用并给我这个错误:

类型错误:预期的字符串或缓冲区

在加载和加载之间切换也转储和转储(我不明白为什么)。正如你所知,我对 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

最佳答案

json.loads() 需要一个字符串。这样做的正确方法是首先构造您的数据并使用 json.dumps 这将为您提供一个 json 对象(实际上是一个字符串)。希望这会有所帮助。

关于 python (JSON): TypeError: expected string or buffer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36262753/

相关文章:

python - 如何将 Dataframe 数据存储到 Firebase 存储?

json - Laravel "Malformed UTF-8 characters, possibly incorrectly encoded",如何修复?

JavaScript 在数组中使用 Indexof 搜索名称

javascript - jQuery在输入标签中推送多个值

python - web.py 骨架代码中 "render._keywords[' globals'] ['render' ] = render"是什么意思?

python - 使用 anaconda 在 Windows 上安装 tensorflow

python - 在 Google App Engine (Python) 中将时区设置为 EST

javascript - jquery.post() 后端响应,但回调函数参数为空

python - 如何同时运行 PHP 和 Web.py

python - 从传感器读取方波信号