0

I'm trying to develop a (really) simple server who an iOS app will interrogate. The Python script has to connect to the MySQL database and return data in JSON format. I can not achieve that it works also with special characters like è or é. This is a short and simplified version of my code with a lot of debugging printing inside...

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import MySQLdb
import json

print ("Content-Type: application/json; charset=utf-8\n\n")  

db = MySQLdb.connect("localhost","root","******","*******" )
    
cursor = db.cursor()

sql = "SELECT * FROM places WHERE name IN (\"Palazzina Majani\")"

try: 
    cursor.execute(sql)
    num_fields = len(cursor.description)
    field_names = [i[0] for i in cursor.description] 
    results = cursor.fetchall() 
    print ("------------------results:")
    print (results)
    output_json = []
    for row in results:
        output_json.append(dict(zip(field_names,row)))
    print ("------------------output_json:")
    print (output_json)
    output = json.dumps(output_json, ensure_ascii=False)
    print ("------------------output:")
    print (output)

except:
    print ("Error")
 
db.close()

And this is what I get with terminal and also with browser:

Content-Type: application/json; charset=utf-8

------------------results:
(('Palazzina Majani', 'kasj \xe8.\xe9', 'palazzina_majani'),)
------------------output_json:
[{'imageName': 'palazzina_majani', 'name': 'Palazzina Majani', 'description': 'kasj \xe8.\xe9'}]
------------------output:
[{"imageName": "palazzina_majani", "name": "Palazzina Majani", "description": "kasj ?.?"}]

How can I manage those special characters (and the mainly used from latin-1)? What if I simply replace single quotes with double quotes from "output_json" insted of using json.dumps?

Thank you!

SOLUTION

As Parfait said in the comments, passing charset='utf8' inside connect() solved the problem!

dot.Py
  • 5,007
  • 5
  • 31
  • 52
Riccardo
  • 38
  • 8
  • Try passing *charset='utf8'* inside `connect()`. – Parfait Dec 29 '17 at 14:45
  • @Parfait If I do this the last `print (output)` raise an exception and print _Error_ as the except block has to do. The error is: `'ascii' codec can't encode character u'\xe8' in position 84: ordinal not in range(128)` – Riccardo Dec 29 '17 at 15:02
  • @Parfait The exception raises on the console BUT if I try the script with browser (and with my app using the complete script) it works! Please, tell me some sources where I can find more information to understand WHY this is the solution... I've been on this for days! – Riccardo Dec 29 '17 at 15:15
  • Why even use ascii? See this [SO post](https://stackoverflow.com/questions/8365660/python-mysql-unicode-and-encoding). – Parfait Dec 29 '17 at 15:26

0 Answers0