0

I'm trying to save json files to csv but I receive the following error:

File "C:\Python\lib\encodings\cp1250.py", line 19, in encode
  return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 20-26: character maps to <undefined>

My script is:

import json

f = open('PlaylistsMondoWorld.csv','w')

with open('PL1.json',encoding='UTF-8') as json_data:
    data = json.load(json_data)
    for r in data ['items']:
        snippet = r ['snippet']
        f.write(snippet ['title']+',')
f.close()

And a part of json file I'm using is:

{
"kind": "youtube#playlist",
"etag": "\"gMxXHe-zinKdE9lTnzKu8vjcmDI/2XhXuZ6FvF_yCAJCF6MLhcWM7no\"",
"id": "PLYXievo3ibiUSj_psEb9dmRNRy9877w8-",
"snippet": {
"publishedAt": "2015-04-08T07:31:15.000Z",
"channelId": "UC1H4TpuRT7msxfqG0jt3sNw",
"title": "FULL MOVIES - AR -  العربية",
"description": "",
"thumbnails": {
 "default": {
  "url": "https://i.ytimg.com/vi/g7l_xbw3ptk/default.jpg",
  "width": 120,
  "height": 90
 },
 "medium": {
  "url": "https://i.ytimg.com/vi/g7l_xbw3ptk/mqdefault.jpg",
  "width": 320,
  "height": 180
 },
 "high": {
  "url": "https://i.ytimg.com/vi/g7l_xbw3ptk/hqdefault.jpg",
  "width": 480,
  "height": 360
 },
 "standard": {
  "url": "https://i.ytimg.com/vi/g7l_xbw3ptk/sddefault.jpg",
  "width": 640,
  "height": 480
 },
 "maxres": {
  "url": "https://i.ytimg.com/vi/g7l_xbw3ptk/maxresdefault.jpg",
  "width": 1280,
  "height": 720
 }
},

Any ideas how to solve this? i saw many posts on Stack Overflow, but haven't found a solution which would help me. So the question actually is, how to save the json to csv with UTF-8 encoding using Python.

Manel
  • 176
  • 4
  • 16
Kuba
  • 5
  • 1
  • 3
  • always add in question full error message (Traceback) There are other usefull information- ie. which line of code makes problem. Mostly problem is not JSON file but Windows console when you try to print this text. – furas Jan 04 '17 at 13:21
  • if you want to save as CSV then maybe use module `csv` – furas Jan 04 '17 at 13:22
  • Possible duplicate of [How can I convert JSON to CSV?](http://stackoverflow.com/questions/1871524/how-can-i-convert-json-to-csv) – WhatsThePoint Jan 04 '17 at 13:23
  • You’re attempting to print something, and that printing fails. See [this question](http://stackoverflow.com/questions/16346914/python-3-2-unicodeencodeerror-charmap-codec-cant-encode-character-u2013-i) for example. – poke Jan 04 '17 at 13:29
  • right, providing full error message makes more sense: Traceback (most recent call last): File "conversion1.py", line 9, in f.write(snippet ['title']+',') File "C:\Python\lib\encodings\cp1250.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode characters in position 20-26: c haracter maps to – Kuba Jan 04 '17 at 13:39

0 Answers0