python格式化json⽂件_python⾃动格式化json⽂件的⽅法本⽂实例讲述了python⾃动格式化json⽂件的⽅法。分享给⼤家供⼤家参考。具体如下:
这⾥主要实现将代码混乱的json⽂件格式化。
还有⼀⼩堆python常⽤算法代码
完整实例代码点击此处。
class JsonFormatter:
def __init__(self,intend=4,name=""):
self.name=name
self.intend=intend
self.stack=[]
self.obj=None
self._source(name)
self.prepare()
@staticmethod
def json_str(s):
return '"'+s+'"'
@staticmethod
def get_source(name):
with open(name,'r') as f:
return ''.ad().split())
def prepare(self):
try:
python怎么读取json文件self.obj=eval(self.source)
except:
raise Exception('Invalid json string!')
def line_intend(self,level=0):
return '\n'+' '*self.intend*level
def parse_dict(self,obj=None,intend_level=0):
self.stack.append(self.line_intend(intend_level)+'{')
intend_level+=1
for key,value in obj.items():
key=self.json_str(str(key))
self.stack.append(self.line_intend(intend_level)+key+':')
self.parse(value,intend_level)
self.stack.append(',')
self.stack.append(self.line_intend(intend_level-1)+'}') def parse_list(self,obj=None,intend_level=0):
self.stack.append(self.line_intend(intend_level)+'[') intend_level+=1
for item in obj:
self.parse(item,intend_level)
self.stack.append(',')
self.stack.append(self.line_intend(intend_level-1)+']') def parse(self,obj,intend_level=0):
if obj is None:
self.stack.append('null')
elif obj is True:
self.stack.append('true')
elif obj is False:
self.stack.append('false')
elif isinstance(obj,(int,long,float)):
self.stack.append(str(obj))
elif isinstance(obj,str):
self.stack.append(self.json_str(obj))
elif isinstance(obj,(list,tuple)):
self.parse_list(obj,intend_level)
elif isinstance(obj,dict):
self.parse_dict(obj,intend_level)
else:
raise Exception('Invalid json type %s!' % obj)
def render(self):
self.parse(self.obj,0)
res_file='good'+self.name
res=''.join(self.stack)
with open(res_file,'w') as f:
f.write(res)
print res
if __name__=="__main__":
jf=JsonFormatter(name="")
希望本⽂所述对⼤家的Python程序设计有所帮助。
如您对本⽂有疑问或者有任何想说的,请点击进⾏留⾔回复,万千⽹友为您解惑!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。