user1192309
user1192309

Reputation: 57

Unicode Error using JSON

I know there have been similar questions posted but I think the issue I'm having is slightly different compared to them. Please bear with me; I have only started using Python 4 months ago and I'm sure my immaturity shows!

I am writing a program that displays LinkedIn data from a CSV file using the Protovis plugin in a dendrogram. The plugin is set up correctly as far as I can see and this is all based off of O'Reilly's Mining the Social Web. However, when I run my code in IDLE, I get the following error message:

Traceback (most recent call last):
 File "C:/Users/Envy 15/Desktop/MASIDendo", line 115, in <module>
    html = open(HTML_TEMPLATE).read() % (json.dumps(json_output),)
  File "C:\Python27\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "C:\Python27\lib\json\encoder.py", line 201, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Python27\lib\json\encoder.py", line 264, in iterencode
    return _iterencode(o, 0)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x96 in position 17: invalid start `byte`

Now as I understand it, the reason for the Unicode error is that there is a non-Unicode character in one of my filenames, however I have checked them and that's not the case. The part of my code it's pointing to is:

html = open(HTML_TEMPLATE).read() % (json.dumps(json_output),)
f = open(os.path.join(os.getcwd(), 'out', OUT), 'w')
f.write(html)
f.close()

print 'Data file written to: %s' % f.name

# Open up the web page in your browser

webbrowser.open('file://' + f.name)

Any help with this would be much appreciated!

Upvotes: 1

Views: 2378

Answers (2)

nfirvine
nfirvine

Reputation: 1539

Sounds like your json_output object has a string in it that's not unicode or unicode-encodable. It's not the filename that's a problem.

Upvotes: 0

Dima Tisnek
Dima Tisnek

Reputation: 11779

check your bases, validate the content of json_data, use repr() or pprint.pprint().

str and unicode objects have methods encode and decode that accept errors argument, like this: "\x66\x89".decode("utf-8", "replace")

json.dumps encodes data into json, it is strange that you pass it json_output as input.

Upvotes: 3

Related Questions