views:

76

answers:

2

When you convert a list of user objects into json, and then convert it back to its original state, do you have to cast?

Are there any security issues of taking a javascript json object and converting it into a python list object?

+1  A: 

You will be responsible for writing python to encode and decode your classes. How are you encoding them? That will have a large bearing on how you decode them. Python will not do either for you if you step beyond dicts, lists, unicode, strings, ints, floats, booleans, and None.

The canonical way to encode custom classes is to subclass json.JSONEncoder and provide a default method. The default method has signature 'self, obj' and returns obj encoded in json if it knows how to and returns super(clsname, self).default(obj) if does not.

If you encode your classes as dicts, then you can write a function that accepts one argument (a decoded dictionary) and returns the decoded object from that. Then pass this function to the constructor for json.JSONDecoder and use the decode method on that instance.

All in all, json is not ideally suited for serializing complex classes. If you can capture the entire state of a function in such a way that it can be passed to the init method, then have at it but if not, then you'll just hurt your head trying.

aaronasterling
+2  A: 

json.dumps(somepython) gives you a valid JSON string representing the Python object somepython (which may perfectly well be a list) and json.loads(ajsonstring) goes the other way 'round -- both without any security issue nor "cast" (?). That's with Python 2.6 or better, using the json module in the standard library. If you're stuck with 2.5 (e.g., for use on Google App Engine), you can use the equivalent third-party module simplejson.

Alex Martelli
What you say isn't at all true for user defined classes. You have to implement a custom encoder to make that work.
aaronasterling
@aaron, `json.loads` will _never_ return "user defined classes" -- there's no such thing in the JSON standard, so, isn't that obvious? If and when you want to dump anything _but_ the JSON-defined types (and/or reload from JSON into non-JSON-defined types), therefore, obviously you need to select and code your own proprietary encoding (presumably to be made known to the Javascript on the other side of the transaction, too;-). This is not at all limited to user-defined classes, btw: plenty of Python's own built-in types (e.g., complex numbers!) are beyond the JSON standards, as well.
Alex Martelli
absolutely correct. As I should have pointed out in my original comment, OP is asking about encoding instances of user defined classes.
aaronasterling