python 格式化Json数据

有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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值