views:

209

answers:

1

I want to transfer some data from python to javascript. I use Django at python side and jQuery at javascript side.

The object I serialize at python side is a dictionary.

Besides simple objects like lists and variables, this dictionary contains instances of SomeClass. To serialize those instances I extendeded simplejson.JSONEncode like this:

class HandleSomeClass(simplejson.JSONEncoder):
    """ simplejson.JSONEncoder extension: handle SomeClass """
    def default(self, obj):
        if isinstance(obj, SomeClass):
            readyToSerialize = do_something(obj)
            readyToSerialize.magicParameter = 'SomeClass'
            return readyToSerialize
        return simplejson.JSONEncoder.default(self, obj)

This way, the SomeClass instances appear in JSON as dictionaries having magicParameter == 'SomeClass' Those instances can be nested at various deph.

Now I would like to recreate those instances at javascript side.

I basically would like to hava a JSON decoder, which will convert all dictionaries with magicParameter == 'SomeClass' to custom javascript objects using a simple object factory:

SomeClass = function( rawSomeClass ) {

    jQuery.extend( this, rawSomeClass ) // jQuery extend merges the newly-created object and the rawSomeClass object

}

and then I could add methods like this to recreate the original objects:

SomeClass.prototype.get = function( arguments ) {
    // function body

}

How to write a decoder, which will scan the JSON object and perform the convertion?

A: 
  1. Eval the JSON string into an object
  2. Run through the values of the object and identify values with magicParameter='SomeClass'
  3. Run those values through a converter
  4. Assign the result back to where the value initially was in the result object
artemb
How do I run through the values? There can be nested dictionaries, and lists.
Uszy Wieloryba
`for (variable in object)` is a simple answer. Or you can read https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Statements/For...in for more details
NilColor
This is a really good article about json parsing on the client side - http://code.flickr.com/blog/2009/03/18/building-fast-client-side-searches/
viksit