Pravitha V
Pravitha V

Reputation: 3308

Accepting json image file in Python

How can we accept json image files in python ? we use josn.loads for data but what about image files?

Upvotes: 3

Views: 20365

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1123400

JSON is a textual format. Since images are opaque binary data, you'd need to encode that data into a textual format.

Base64 is most commonly used for such data, which python can handle just fine with the base64 module:

import base64
import json

image = base64.decodestring(json.dumps(data)['image'])

This is what Twitter supports for updating your profile image.

However, using JSON for image data is not a good idea for all but very small images. The json parser included in python will easily overload with a large payload like a decently sized image.

You'd be better off providing a REST API that accepts images using a PUT or POST request instead, then communicate about the image using URLs.

Upvotes: 9

Aesthete
Aesthete

Reputation: 18848

JSON is JavaScript Object Notation. It is used to convey information with the use of basic types, strings, integers, floats, booleans etc.

It can be used to convey meta data about resources, but not typically the resources themselves.

For instance, you might receive a JSON object like the following:

a = '''{
  'imageUrl': '/images/image.png',
  'imageName': 'My Image'  
}'''
decoded = json.loads(a)

Typically you use this representational information to retrieve the resource on their own. You could do this in python with the standard library's networking modules.

import urllib2
img = urllib2.urlopen(decoded.imageUrl).read()

Upvotes: 3

Related Questions