Created
July 17, 2018 16:42
-
-
Save h3nryza/384d48a66d1c0a95377d80b5ff124151 to your computer and use it in GitHub Desktop.
Easy Json serialize / Deserialize in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding: <utf-8> -*- | |
from __future__ import print_function | |
import json | |
try: | |
from types import SimpleNamespace as Namespace | |
except ImportError: | |
# Python 2.x fallback | |
from argparse import Namespace | |
#This converts your data to Json | |
def serialize(self, ServerName="something", port=1, | |
username="something", password="something", | |
routingMap=[{"ApplicationName":"something","dataFileLocation":"./","QueueName":"something"}]): | |
toBeConvertedToJson = {} | |
toBeConvertedToJson["ServerName"] = ServerName | |
toBeConvertedToJson["port"] = port | |
toBeConvertedToJson["username"] = self.crypto.encrypt(username) | |
toBeConvertedToJson["password"] = self.crypto.encrypt(password) | |
toBeConvertedToJson["Description"] = "This application pushed application information to Rabbitmq" | |
# Routing Map, iterate though items and convert to UTF-8 | |
toBeConvertedToJson["routingMap"] = routingMap | |
#rabbitmqinformation["routingMap"] = self.makeRoutes() | |
return json.dumps(toBeConvertedToJson, indent=4, encoding="utf-8") | |
#This uses namespaces to return a dictionary value to make it easier to access the json values | |
def deserialize(self, data): | |
dataDic = json.loads(data, object_hook=lambda d: Namespace(**d)) | |
self.servername = dataDic.ServerName.encode("utf-8") | |
self.port = dataDic.port | |
self.routingMap = dataDic.routingMap | |
self.username = self.crypto.decrypt(dataDic.username).encode("utf-8") | |
self.password = self.crypto.decrypt(dataDic.password).encode("utf-8") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment