David542
David542

Reputation: 110209

Json encode a complex dict

How would I json encode the following dict:

data = {
    'name': 'david',
    'avatar': open('file.jpg').read()
}

When I try doing json.dumps(data) I get a UnicodeDecodeError.

Upvotes: 2

Views: 652

Answers (2)

Daniel
Daniel

Reputation: 42758

So you try to encode a picture in json. If you want to display it on a web page, consider using a data-url-encoding:

image = "data:image/jpg;base64,%s" % ''.join(open('file.jpg').read().encode('base64').split())
data = {
    'name': 'david',
    'avatar': image,
}
json_data = json.dumps(data)

or if you only need the binary data, simply use:

image = open('file.jpg').read().encode('base64')
data = {
    'name': 'david',
    'avatar': image,
}
json_data = json.dumps(data)

#decode
data = json.loads(json_data)
image = data['avatar'].decode('base64')

Upvotes: 2

user2555451
user2555451

Reputation:

You must be using Python 2.x. Since you have Unicode data in the string, you need to make it a Unicode string literal:

>>> import json
>>> data = {
...     'name': 'david',
...     'avatar': u'\xed\xb3\x1cW\x7f\x87\x1c\xb9*Pw\x9a#W\x05\xeaNs\xe4\xaa@\xddi\x8e\\\x15\xa8;\xcd\x91\xab\x02u\xa79rU\xa0\xee4\xf7K\xb9\x05{t\x02\xc6I\xb6\xaa\xbf\x00\x00\x00\x00IEND\xaeB`\x82...'
... }
>>> json.dumps(data)
'{"name": "david", "avatar": "\\u00ed\\u00b3\\u001cW\\u007f\\u0087\\u001c\\u00b9*Pw\\u009a#W\\u0005\\u00eaNs\\u00e4\\u00aa@\\u00ddi\\u008e\\\\\\u0015\\u00a8;\\u00cd\\u0091\\u00ab\\u0002u\\u00a79rU\\u00a0\\u00ee4\\u00f7K\\u00b9\\u0005{t\\u0002\\u00c6I\\u00b6\\u00aa\\u00bf\\u0000\\u0000\\u0000\\u0000IEND\\u00aeB`\\u0082..."}'
>>>

By placing u before the string literal, you tell Python to treat the string as Unicode.

Note that this is unnecessary in Python 3.x since all strings are now Unicode by default.

Upvotes: 2

Related Questions