I tried to create a class that can easily serialize Json in Python

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.

Target

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

Source code

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

How to use

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

I tried to create a class that can easily serialize Json in Python
I tried to develop a Formatter that outputs Python logs in JSON
I want to create a priority queue that can be updated in Python (2.7)
I want to create a window in Python
How to create a JSON file in Python
I want to easily implement a timeout in python
I tried to implement a pseudo pachislot in Python
I tried to easily create a fully automatic attendance system with Selenium + Python
I tried to create API list.csv in Python from swagger.yaml
I tried to implement a one-dimensional cellular automaton in Python
I tried "a program that removes duplicate statements in Python"
I tried "How to get a method decorated in Python"
I created a class in Python and tried duck typing
I tried to make a stopwatch using tkinter in python
I tried to create a class to search files with Python's Glob method in VBA
I tried to create a linebot (implementation)
I tried to create a server environment that runs on Windows 10
I tried to implement PLSA in Python
I tried to implement permutation in Python
[Python / Django] Create a web API that responds in JSON format
I tried to implement PLSA in Python 2
[Python] A memo that I tried to get started with asyncio
Create a JSON object mapper in Python
I tried to create a list of prime numbers with python
I tried to implement a misunderstood prisoner's dilemma game in Python
I tried to implement ADALINE in Python
I tried to make a generator that generates a C # container class from CSV with Python
I tried to implement PPO in Python
I tried to create a Python script to get the value of a cell in Microsoft Excel
I tried to easily create a high-precision 3D image with one photo [1]. (Depth can now be edited in PNG.)
[python] I made a class that can write a file tree quickly
A story that didn't work when I tried to log in with the Python requests module
I made a web application in Python that converts Markdown to HTML
I tried to create a program to convert hexadecimal numbers to decimal numbers with python
[Outlook] I tried to automatically create a daily report email with Python
I tried to create a sample to access Salesforce using Python and Bottle
I tried to implement a card game of playing cards in Python
I want to easily create a Noise Model
A memo that I wrote a quicksort in Python
I tried playing a typing game in Python
I wrote a class in Python3 and Java
You can easily create a GUI with Python
[Memo] I tried a pivot table in Python
I tried to implement TOPIC MODEL in Python
Python: Create a class that supports unpacked assignment
I tried adding a Python3 module in C
I tried to implement selection sort in python
Create a plugin that allows you to search Sublime Text 3 tabs in Python
I registered PyQCheck, a library that can perform QuickCheck with Python, in PyPI.
I tried using the Python library "pykakasi" that can convert kanji to romaji.
I tried to explain what a Python generator is for as easily as possible.
When I tried to create a virtual environment with Python, it didn't work
I made a familiar function that can be used in statistics with Python
[Azure] I tried to create a Linux virtual machine in Azure of Microsoft Learn
[Python] I tried to make a Shiritori AI that enhances vocabulary through battles
I tried to implement what seems to be a Windows snipping tool in Python
I tried to graph the packages installed in Python
Parse a JSON string written to a file in Python
I tried to create a table only with Django
I tried to draw a route map with Python
I want to write in Python! (2) Let's write a test