I convert python dicts with simplejson, but I’d like to customise the output for some defined keys.
for example, I’d like the keys callback and scope to be always rendered with no surrounding quotes so the javascript can interpret the data and not read it as a string.
example desired output :
"data":{
"name":"Julien"
,"callback":function() {alert('hello, world');}
,"params":{
"target":"div2"
,"scope":this
}
}
Notice the callback and scope keys have no surrounding quotes in their values.
I’ve tried create a custom class and subclass JSONencoder with no luck.
class JsonSpecialKey(object):
def __init__(self, data):
self.data = data
class JsonSpecialEncoder(simplejson.JSONEncoder):
def default(self, obj):
if isinstance (obj, JsonSpecialKey):
# how to remove quotes ??
return obj.data
return simplejson.JSONEncoder.default(self, obj)
d = {'testKey':JsonSpecialKey('function() {alert(123);}')}
print simplejson.dumps(d, cls=JsonSpecialEncoder, ensure_ascii=False, indent=4)
I know the resulting JSON may be invalid in the JSON recommendations but it is important to some JS applications.
I’ve tried some regex workarounds but it’s getting complex for multilines and inline functions with data inside.
Thank you !
I succeed by modifying json code
EDITED:precision of the code I modified
from
json.encodeI took the function_make_iterencodeadding something like
at three places
from
JsonEncoderI took the methoditerencodebut I just forced the
_iterencodeto be my custom function_make_iterencodeI hope it’s clear