1

I want to run this code block :

>>> json1 = json.loads("""[{"categoryId":"32","nameAr":"\u0627\u0643\u0644 \u0633\u0631\u064a\u0639","nameEn":"Fast Food"}]""")
>>> file1 = open("test.csv","w")
>>> fieldnames = json1[0].keys()
>>> writer = csv.DictWriter(file1, fieldnames=fieldnames)
>>> writer.writeheader()
>>> writer.writerow(json1[0])

but I get this error :'ascii' codec can't encode characters in position 0-2, I think this happened because I should encode json1 values to utf-8 , How could I do that ?

mattn
  • 7,571
  • 30
  • 54
david
  • 3,310
  • 7
  • 36
  • 59
  • 1
    This has nothing to do with JSON encoding but with the way you are writing the data. That file is configured to use ASCII encoding, which doesn't work since the JSON contains non-ASCII chars. You might be able to tell the JSON encoder to escape those, so that only ASCII is used or change the file encoding. – Ulrich Eckhardt Dec 25 '14 at 11:34
  • 1
    You decode *from* UTF-8, and *encode* to UTF-8. – Ignacio Vazquez-Abrams Dec 25 '14 at 11:35
  • 1
    It is a duplicate, only change one line `writer.writerow({k.encode('utf8'): v.encode('utf8') for k, v in json1[0].iteritems()})` – jamylak Dec 25 '14 at 11:43
  • @jamylak thank you, that's what I was searching for :) – david Dec 25 '14 at 11:45

1 Answers1

0

Use the unicode csv library

writer = unicodecsv.DictWriter(file1, fieldnames=fieldnames)

If you don't have it install it with pip or easy_install

Oussama Jilal
  • 7,669
  • 2
  • 30
  • 53