开发者

JSON python to javascript

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

开发者_JAVA技巧

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?


  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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜