Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

1 Answer

  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
share|improve this answer
 
How do I run through the values? There can be nested dictionaries, and lists. –  uszywieloryba Jan 29 '10 at 11:22
 
for (variable in object) is a simple answer. Or you can read developer.mozilla.org/En/Core_JavaScript_1.5_Reference/… for more details –  NilColor Jan 29 '10 at 14:36
 
This is a really good article about json parsing on the client side - code.flickr.com/blog/2009/03/18/… –  viksit Feb 1 '10 at 1:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.