Home Up Back Forward Leave Message


Overview

The code is available for download from:

JSON handling in Python

Please note that I'm using Python 3 in all examples.

It is actually very easy to encode something as JSON in python, for example:
    import json

    logon = {"username": "daffy", "password": "duck"}
    result = json.dumps(logon)
The only drawback is that you cannot encode an object directly without coding an encoder for it, but what you can do is to convert the object to a dictionary and python knows how to encode a dictionary. It will actually creates a JSON object from a dictionary.
    import json

    class Message:
        .........
        def __iter__(self):
            return iter([('messageid',self.messageid),('username',self.username),('message',self.message)])

    msg = Message(.....)
    result = json.dumps(dict(msg))
The __iter__ definition is to make the fields iterable, if you apply dict to it now python will generate a dictionary.

To decode a JSON input, you normally first has to cast the byte array to a string by using:
    strval = bytebuf.decode("utf-8")
To decode the string value now you just do the following:
    decodedval = json.loads(strval)
All objects are converted to dictionaries, list stay lists as well as all the other primative values. So you just have to remember that the JSON object is now a dictionary and you have to access it as such.
    val = json.loads('{"username": "daffy", "password": "duck"}')
    print("The user is " + val["username"])

HTTP handling of calls

On the server side it is relatively straight forward, we just write handlers for each of the functions. Each function is called with the query information, but we will only use the body. The read the body of a post request:
    def handleFunction(self,qry):
        body = self.rfile.read(int(self.headers.get('Content-Length'))).decode("utf-8")

This can then be decoded from JSON as mentioned above.

To call a service (from the client) the following is done:
def callService(call,callbody):
    params = json.dumps(callbody)
    headers = {"Content-type": "application/json", "Accept": "text/plain"}
    conn = http.client.HTTPConnection("localhost:8080")
    conn.request("POST", "/" + call, params, headers)
    response = conn.getresponse()
    data = response.read()
    conn.close()
    return json.loads(data.decode("utf-8"))    
This function gets parameters and the actual data to put in the post. The data is converted to json. Headers are created to indicate that we want to send JSON. A connection is made to the server on the right port and then a request is made to the function with the JSON body and headers. The response is read and decoded and returned.