The code is available for download from:
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.
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"])
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.
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.