本文实例讲述了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程序设计有所帮助。

pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)他们areStoredIncoNtiguulMemoryBlocks,mayrequireRealLealLocationWhenAppendingItems,EmpactingPerformance.2)LinkesedlistSwoldOfferefeRefeRefeRefeRefficeInsertions/DeletionsButslowerIndexeDexedAccess,Lestpypytypypytypypytypy

pythonoffersFourmainMethodStoreMoveElement Fromalist:1)删除(值)emovesthefirstoccurrenceofavalue,2)pop(index)emovesanderturnsanelementataSpecifiedIndex,3)delstatementremoveselemsbybybyselementbybyindexorslicebybyindexorslice,and 4)

toresolvea“ dermissionded”错误Whenrunningascript,跟随台词:1)CheckAndAdjustTheScript'Spermissions ofchmod xmyscript.shtomakeitexecutable.2)nesureThEseRethEserethescriptistriptocriptibationalocatiforecationAdirectorywherewhereyOuhaveWritePerMissionsyOuhaveWritePermissionsyYouHaveWritePermissions,susteSyAsyOURHomeRecretectory。

ArraysarecrucialinPythonimageprocessingastheyenableefficientmanipulationandanalysisofimagedata.1)ImagesareconvertedtoNumPyarrays,withgrayscaleimagesas2Darraysandcolorimagesas3Darrays.2)Arraysallowforvectorizedoperations,enablingfastadjustmentslikebri

ArraySaresificatificallyfasterthanlistsForoperationsBenefiting fromDirectMemoryAcccccccCesandFixed-Sizestructures.1)conscessingElements:arraysprovideconstant-timeaccessduetocontoconcotigunmorystorage.2)iteration:araysleveragececacelocality.3)

ArraySareBetterForlement-WiseOperationsDuetofasterAccessCessCessCessCessCessAndOptimizedImplementations.1)ArrayshaveContiguucuulmemoryfordirectAccesscess.2)列出sareflexible butslible dueTopotentEnallymideNamicizing.3)forlarargedAtaTasetsetsetsetsetsetsetsetsetsetsetlib

在NumPy中进行整个数组的数学运算可以通过向量化操作高效实现。 1)使用简单运算符如加法(arr 2)可对数组进行运算。 2)NumPy使用C语言底层库,提升了运算速度。 3)可以进行乘法、除法、指数等复杂运算。 4)需注意广播操作,确保数组形状兼容。 5)使用NumPy函数如np.sum()能显着提高性能。

在Python中,向列表插入元素有两种主要方法:1)使用insert(index,value)方法,可以在指定索引处插入元素,但在大列表开头插入效率低;2)使用append(value)方法,在列表末尾添加元素,效率高。对于大列表,建议使用append()或考虑使用deque或NumPy数组来优化性能。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

记事本++7.3.1
好用且免费的代码编辑器