Skip to content

Instantly share code, notes, and snippets.

@NrI3
Last active March 25, 2020 16:30
Show Gist options
  • Save NrI3/47d6887b399aa969f8849b5fa8c64863 to your computer and use it in GitHub Desktop.
Save NrI3/47d6887b399aa969f8849b5fa8c64863 to your computer and use it in GitHub Desktop.
[Python] json to object
###
## Writed By [email protected]
###
import json
class Object:
pass
class Pyo(object):
_file = None
_json = None
_dict = None
_object = Object()
def __init__(self, json_path=''):
self.__load_json(json_path)
self.__create_object()
def __load_json(self, path):
try:
self._file = open(path,'r')
self._json = self._file.read()
self._dict = json.loads(self._json)
except Exception as e:
print(e)
exit()
def __create_object(self):
self.__iterate(self._dict, self._object)
return self._object
def __iterate(self, l, r):
for o in l:
if isinstance(o,str):
setattr(r, o, None)
# String
if isinstance(l[o],str):
setattr(r, o, l[o])
# Int
elif isinstance(l[o],int):
setattr(r, o, l[o])
# Dict
elif isinstance(l[o],dict):
setattr(r, o, Object())
self.__iterate(l[o], getattr(r,o) )
# Add More if u want
def obj(self):
return self._object
def dic(self):
return self._dict
def json(self):
return self._json
class Jo:
def __new__(cls, path):
o = Pyo(path).obj()
return o
####
## Import all module in IDLE for interact with object
#
# import sys
# sys.append('/path_of_module/')
# from MPyo import *
# o = Jo('./file.json')
## Now in your IDLE write and press tab and enjoy!
#> o.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment