开发者

JSON python to javascript

开发者 https://www.devze.com 2022-12-18 16:32 出处:网络
I want to transfer some data from python to javascript. I use Django at python side and jQuery at javascript side.

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

精彩评论

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