Python unicode error

This is the essence of the problem. I am trying to get data from a REST API call and store it in a database. Then I run a few queries to find out the TOP 3 users. I could not pack all the list values ​​that I get from MySQL into a JSON file.

I can’t get past the next problem.

File "/Users/id1/Downloads/user1.py", line 58, in get_last_three_installed_user results.append (dict (zip (columns, row)))

TypeError: 'unicode' object cannot be called

This is the result of an SQL query.

+----------------+--------+-------------+------------+-----------------+ | name | gender | nationality | registered | registered_date | +----------------+--------+-------------+------------+-----------------+ | mélissa robin | female | FR | 1437761753 | 2015-07-24 | | agathe fabre | female | FR | 1437002837 | 2015-07-15 | | soline morin | female | FR | 1436138376 | 2015-07-05 | +----------------+--------+-------------+------------+-----------------+ 

If I try str (name), I get the following error:

name = str (json_dict ["results"] [result] ["user"] ["name"] ["first"]) + "" + str (json_dict ["results"] [result] ["user"] [ "name"] ["last"])

UnicodeEncodeError: codec 'ascii' cannot encode character u '\ xe4' at position 1: serial number not in range (128)

Here is my code:

 def get_last_three_installed_user(file_type): count_sql = "select name,gender,nationality,registered,DATE_FORMAT(from_unixtime(registered), '%Y-%m-%d') registered_date from install_user order by from_unixtime(registered) desc limit 3 " curs.execute(count_sql) columns = [column[0] for column in curs.description] results = [] if file_type == 'csv': fp = open('user_list.csv', 'w') csvFile = csv.writer(fp) rows = curs.fetchall() csvFile.writerows(rows) else: with open('file_count.json', 'w') as outfile: for row in curs.fetchall(): results.append(dict(zip(columns, row))) print results output = {"TableData": results} json.dump(output, outfile, sort_keys = True, indent = 4, ensure_ascii=False) 
+4
source share
1 answer

This code pretty much took care of that.

 def get_last_three_installed_user(file_type): count_sql = "select name,gender,nationality,registered,DATE_FORMAT(from_unixtime(registered), '%Y-%m-%d') registered_date from install_user order by from_unixtime(registered) desc limit 1,3 " curs.execute(count_sql) results = [] dict1 ={} if file_type == 'csv': fp = open('user_list.csv', 'w') csvFile = csv.writer(fp) rows = curs.fetchall() csvFile.writerows(rows) else: with open('file_count.json', 'w') as outfile: for row in curs.fetchall(): for idx, col in enumerate(curs.description): dict1[col[0]] = row[idx] results.append(dict1) output = {"TableData": results} json.dump(output, outfile, sort_keys = True, indent = 4, ensure_ascii=False) 
0
source

All Articles