【问题标题】:I'm trying to access some json data from a my sql server我正在尝试从我的 sql 服务器访问一些 json 数据
【发布时间】:2018-01-16 19:34:42
【问题描述】:

请注意,我是 python 新手。 我尝试使用 python 从 MySQL 服务器访问数据。 到目前为止,我已经连接到服务器并获取了数据,但是当我解析数据时出现了问题。 我得到的错误如下。

TypeError:预期的字符串或缓冲区

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)

【问题讨论】:

    标签: python mysql json


    【解决方案1】:

    TypeError: expected string or buffer 清楚地暗示了问题。

    您可以使用print result 来验证类型。

    --

    cursor.fetchone()

    此方法检索查询结果集的下一行并返回单个序列,如果没有更多行可用,则返回。文档参考here

    ==

    json.loads(s)

    此方法使用此转换表将包含 JSON 文档的 str 或 unicode 实例反序列化为 Python 对象。参考this

    --

    所以,我想也许你不需要 json.loads... 因为结果已经是一个 python 对象。

    【讨论】:

    • 类型是元组,不知道怎么解析元组??
    • 你想用'result'或'x'对象做什么? touple 是一个序列对象,就像 List 一样
    • 感谢您的帮助,您的回答确实帮助了我的理解,我导入的数据被自动格式化为元组,我必须独立访问每个项目才能使用 json.loads()跨度>
    【解决方案2】:

    json 加载 -> 从表示 json 对象的字符串中返回一个对象。

    json dumps -> 从一个对象返回一个表示 json 对象的字符串。

    所以你的json.loads 正在寻找一个字符串表示。所以你最好先做 json.dumps 然后再做 json.loads。

    这应该可以解决。

    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)
    

    【讨论】:

      【解决方案3】:

      默认情况下,Cursor 类将行作为元组返回。

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

      打印(结果)你得到("foo", )

      你可以这样做来得到你的结果

          x = result[0]
      

      在光标中包含 MySQLdb.cursors.DictCursor 以将行作为字典返回。然后您可以通过名称访问它们。

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

      打印(结果)你会得到{"answer_option": "foo"}

      您可以像这样访问您的结果:

          x = result['answer_option']
      

      【讨论】:

        猜你喜欢
        • 2018-09-21
        • 2022-01-25
        • 2018-10-30
        • 1970-01-01
        • 1970-01-01
        • 2015-05-26
        • 2022-06-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多