Organize data sent between client-server
Question: Pardon me if this has been addressed before, but how do I organize data
exchanged between client and server in python application (sockets)?

Let's say I have some elements I have to send - strings, tuples, dicts:

    
    
    "hello world", (1, 2, 3), {"k": "v"}
    

What I currently do is I simply convert everything to string - call `repr()`
before sending and `eval()` after receiving. This obviously seem a bit
redundant.

How should I send these chunks of data? Is there a convention? Preferred
format? How do I compress it?


Answer: JSON is what you're looking for. If you have an object and you import the JSON
functions:

    
    
    from json import dumps, loads
    

you can use `dumps(obj)` to encode into JSON and `loads(str)` to convert a
JSON string back to an object. For example:

    
    
    dumps([[1,2,3],{"a":"b", "c":"d"}])
    

yields `'[[1, 2, 3], {"a": "b", "c": "d"}]'` and

    
    
    loads('[[1, 2, 3], {"a": "b", "c": "d"}]')
    

yields `[[1, 2, 3], {u'a': u'b', u'c': u'd'}]`.

