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?
- Eval the JSON string into an object
- Run through the values of the object and identify values with magicParameter='SomeClass'
- Run those values through a converter
- Assign the result back to where the value initially was in the result object
精彩评论