Thursday, August 14, 2008

Joose now supports jsonpickle

Joose now supports jsonpickle. (At least if you check out the latest SVN).
This gives all the Python programmers the chance to transfer dumps of their Python objects via http to the browser and then instantiate those objects using JavaScript and do method calls on them.

Here is a code example stolen from the jsonpickle homepage:
>>> import jsonpickle
>>> from jsonpickle.tests.classes import Thing

# Create an object.
>>> obj = Thing('A String')
>>> print
A String

# Use jsonpickle to transform the object into a JSON string.
>>> pickled = jsonpickle.dumps(obj)
>>> print pickled
{"child": null, "classname__": "Thing", "name": "A String", "classmodule__": "jsonpickle.tests.classes"}

And here is how you would use the pickled Python object with Joose:
Module("jsonpickle.tests.classes", function () {
Class("Thing", {
does: Joose.Storage.jsonpickle,
has: {
child: {
is: "rw"
name: {
is: "rw"

var thing = JSON.parse('{"child": "Robert", "classname__": "Thing", "name": "A String", "classmodule__": "jsonpickle.tests.classes"}');

Of course you may add many more methods to your Joose classes and use them like real objects.

With a simple JSON.stringify(thing) you can send the data back to Python. (You need to call Joose.Storage.Unpacker.jsonpickle.patchJSON(); to be able to use JSON.stringify directly)

No comments: