You need to handle Json in Python, and it's a built-in feature It was a little difficult to handle, so it will be easier to handle Json with Python. I created a class
It's the first time I've touched Python properly, so it's a little strange to use. It may be in an existing feature in the first place.
When working with Json in Python You can't do it between Python and Json without Map. In this case, in order to classify it, you have to describe it for each class, Also, when outputting Json from a class, you have to write the process for each class. This is ** very annoying **
Therefore, it is automatically serialized from Json key and variable name. Create a class that will be converted to Json from the variable name
This class looks like this.
JsonAdapter.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import json
class JsonAdapter(object):
#Serialize from json
def Serialize(self, argJsonData) :
jsonData = argJsonData
if isinstance(argJsonData, basestring ) :
jsonData = json.loads(argJsonData)
for key in self.__dict__.keys():
if isinstance(getattr(self,key), JsonAdapter ) or getattr(self,key) == None :
valclass = getattr(self,key)
if valclass == None :
valclass = getattr(sys.modules["Classes.DataPDO"],key)()
valclass.Serialize(jsonData[key])
setattr(self,key, valclass)
elif isinstance(getattr(self,key), int ) :
setattr(self,key, int(jsonData[key]))
else :
setattr(self,key, jsonData[key])
#Output Json
def ToJson(self):
jsonDict = self.__ToDictionary()
jsonstring = json.dumps(jsonDict, ensure_ascii=False)
return jsonstring
#Create a map
def __ToDictionary(self):
jsonDict = {}
for key in self.__dict__.keys():
if isinstance(getattr(self,key), JsonAdapter ) :
jsonDict.update({key : getattr(self,key).__ToDictionary()})
else :
jsonDict.update({key : getattr(self,key)})
return jsonDict
If you explain lightly
def Serialize(self, argJsonData) :
Now, create a Dictionary from json once,
The value is taken with the variable name as the key.
In the case of a class, the class is generated and serialized again.
ToJson(self):
Then, on the contrary, create a Dictionary with the variable name as the key,
Jsonized
The sample code is below.
sample.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import JsonAdapter
class Test(JsonAdapter.JsonAdapter):
def __init__(self):
self.num = 0
self.str = ""
self.test2 = Test2()
class Test2(JsonAdapter.JsonAdapter):
def __init__(self):
self.num = 0
self.str = ""
if __name__ == "__main__":
json = """{"test2": {"num": 200, "str": "def"}, "num": 100, "str": "abc"}"""
test = Test()
#initial state
print test.ToJson()
test.Serialize(json)
#After serialization
print test.ToJson()
Output result
{"test2": {"num": 0, "str": ""}, "num": 0, "str": ""}
{"test2": {"num": 200, "str": "def"}, "num": 100, "str": "abc"}
The initial state and the result after serialization are output. You can confirm that it can be serialized normally and that there is no problem with the output.
Note that it needs to be inherited by the PDO class. The point is that the variable name and key name must be unified.
that's all. I thought I touched it properly Python is interesting, isn't it?
Recommended Posts