esac
esac

Reputation: 24685

Data exchange for Python?

Just getting started with Python, but the first goal is to create a web service. I plan on using werkzeug for this, however, all I will be doing is writing a client to interface with it. How would I go about exchanging objects between the 2 systems? Is there anything similar to JSON for Python?

EDIT: A couple mentions of JSON, but my main problem is that I can't serialize a class? I sort of thought that was what JSON could do?

class User():
    def __init__(self, first, last, age):
        self.first = first
        self.last = last
        self.age = age

user = User("John", "Doe", 25)
json.dumps(user)

TypeError: <__main__.User instance at 0x02ABBEE0> is not JSON serializable

I know what you are serializing in JSON isn't necessarily a class, it is an object, but you can still reference it almost as such:

    var mailingAddress = { 
     "Address"    :   "123 Anywhere St.", 
     "City"       :   "Springfield", 
     "PostalCode" :   99999
};
alert("The package will be shipped to postal code " + mailingAddress.PostalCode);

Upvotes: 0

Views: 549

Answers (3)

J&#252;rgen Strobel
J&#252;rgen Strobel

Reputation: 2248

json cannot represent arbitrary python classes. It supports numbers, strings and dicts. The latter is really the same as an object in javascript proper, but it ain't in python.

If you need JSON and cannot use pickle because you want to deliver to javascript in a browser, simply json.dump() a dict made up on the fly from your object:

json.dumps({
    'first': user.first,
    'last': user.last,
    'age': user.age,
})

If you want you can create helpers to reduce some duplication.

def dumpObject(obj, *properties):
    data = dict((p, getattr(obj, p)) for p in properties)
    return json.dumps(data)

dumpObject(user, 'first,' 'last', 'age')

And probably improve this even further by reflection. YMMV.

Upvotes: 0

Raymond Hettinger
Raymond Hettinger

Reputation: 226574

Sounds like you're looking to use pickle instead of json -- pickles are Python specific but can handle user classes as well as dicts:

>>> class User():
    def __init__(self, first, last, age):
        self.first = first
        self.last = last
        self.age = age

>>> user = User("John", "Doe", 25)
>>> import pickle
>>> s = pickle.dumps(user)
>>> del user
>>> user = pickle.loads(s)    # reconstruct the object
>>> print vars(user)
{'age': 25, 'last': 'Doe', 'first': 'John'}

If you need a variant that is language independent, look at PyYAML and the YAML spec at http://yaml.org

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799170

Python has had native JSON support since 2.6 via the json module. Previous versions have had to use external libraries, SimpleJson being the most common.

Upvotes: 4

Related Questions