有2种方式处理Json数据,1是通过自带的json模块,通过json.loads和json.dumps方法进行处理。2是自己写模块处理json模块。本文讲的是第2种。
为什么要自己写模块调用呢,因为遇到一个问题,自带的json模块处理的json数据排序被修改了,虽说json格式是无序的且排序对调用不重要,但是有时格式化json就是阅读需求的时候就很讨厌了,超级讨厌!!! 有时格式化后末尾的数据跑开头了,引起阅读障碍了,所以本文才会自己写模块处理json数据,保证能按照默认排序展示数据。
具体代码如下:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# autor chenlong
import UserString
def formatJson(jsonStr):
if (None == jsonStr and '' == jsonStr):
return ''
__bu = UserString.MutableString('')
__last = '\0'
__current = '\0'
__indent = 0
isInQuotationMarks = False
for i in jsonStr:
__last = __current
__current = i
if(__current == '"'):
if(__last != '\\'):
isInQuotationMarks = not isInQuotationMarks
__bu.append(__current)
elif(__current == '{'):
__bu.append(__current)
if(not isInQuotationMarks):
__bu.append('\n')
__indent += 1
__addIndentBlank(__bu,__indent)
elif(__current == '['):
__bu.append(__current)
if(not isInQuotationMarks):
__bu.append('\n')
__indent += 1
__addIndentBlank(__bu,__indent)
elif(__current == '}'):
if(not isInQuotationMarks):
__bu.append('\n')
__indent -= 1
__addIndentBlank(__bu,__indent)
__bu.append(__current)
elif(__current == ']'):
if(not isInQuotationMarks):
__bu.append('\n')
__indent -= 1
__addIndentBlank(__bu,__indent)
__bu.append(__current)
elif(__current == ','):
__bu.append(__current)
if(__last != '\\' and (not isInQuotationMarks)):
__bu.append('\n')
__addIndentBlank(__bu,__indent)
else:
__bu.append(__current)
return __bu
def __addIndentBlank(bu,indent):
for i in range(indent):
bu.append('\t')
end