本文实例讲述了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=self.get_source(name) self.prepare() @staticmethod def json_str(s): return '"'+s+'"' @staticmethod def get_source(name): with open(name,'r') as f: return ''.join(f.read().split()) def prepare(self): try: 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="json.txt") jf.render()
希望本文所述对大家的Python程序设计有所帮助。

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

ThefastestmethodforlistconcatenationinPythondependsonlistsize:1)Forsmalllists,the operatorisefficient.2)Forlargerlists,list.extend()orlistcomprehensionisfaster,withextend()beingmorememory-efficientbymodifyinglistsin-place.

ToinsertelementsintoaPythonlist,useappend()toaddtotheend,insert()foraspecificposition,andextend()formultipleelements.1)Useappend()foraddingsingleitemstotheend.2)Useinsert()toaddataspecificindex,thoughit'sslowerforlargelists.3)Useextend()toaddmultiple

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download
The most popular open source editor

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools
