Skip to content

JSON type fails in Python 3 w/ any string, Python 2 w/ non-ascii data #488

@zzzeek

Description

@zzzeek

The JSON string comes back as bytes on Python 3 which is not what json.loads() expects. This is also inconsistent vs. mysqlclient. I'm not 100% sure there isn't something else that makes this work, since I had some trouble reproducing and I thought maybe it was working in 0.7.1, but now it's not working there either.

import MySQLdb

import pymysql


import json

def run_test(dbapi):
    print("Running DBAPI: %s" % dbapi)
    conn = dbapi.connect(user='scott', passwd='tiger', db="test", charset='utf8', use_unicode=0)
    cursor = conn.cursor()
    cursor.execute("drop table if exists json_test")
    cursor.execute("create table json_test (data JSON)")
    cursor.execute("insert into json_test (data) values (%s)", ['{"foo": "bar"}'])
    cursor.execute("select data from json_test")
    result = cursor.fetchone()[0]
    print(json.loads(result))

run_test(MySQLdb)
run_test(pymysql)

output:

Running DBAPI: <module 'MySQLdb' from '/opt/python3.5/lib/python3.5/site-packages/MySQLdb/__init__.py'>
{'foo': 'bar'}
Running DBAPI: <module 'pymysql' from '/opt/python3.5/lib/python3.5/site-packages/pymysql/__init__.py'>
Traceback (most recent call last):
  File "test.py", line 20, in <module>
    run_test(pymysql)
  File "test.py", line 17, in run_test
    print(json.loads(result))
  File "/opt/python3.5/lib/python3.5/json/__init__.py", line 312, in loads
    s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions