python json 顺序_Python Json数据排序

# format a json object, indent on various layers

###

#NOTES:

#True -> true

#False -> false

#None -> null

#u'XXXXX' -> 'XXXXX'

#'XXXXX' -> "XXXXX"

# when saving json object to a file, better use json.dump() rather than text write

###

def format(jsonNode, level=0):

INDENT = '\t'

NEWLINE = '\n'

if isinstance(jsonNode, dict):

longStr = '{'+NEWLINE

keys = jsonNode.keys()

for index in range(len(keys)):

key = keys[index]

value = jsonNode[key]

formattedValue = format(value, level + 1)

if formattedValue.endswith(NEWLINE):

formattedValue = formattedValue[:-len(NEWLINE)]

if index != len(keys) - 1:

# not yet the last one

longStr += '{}"{}": {},{}'.format(INDENT*level, key, formattedValue, NEWLINE)

else:

# the last one

longStr += '{}"{}": {}{}'.format(INDENT*level, key, formattedValue, NEWLINE)

longStr += INDENT * level + '}'+NEWLINE

if level == 0:

# final fix before returning

longStr = longStr.replace(NEWLINE+NEWLINE,NEWLINE)

longStr = longStr.replace('}'+NEWLINE+','+INDENT , '},'+NEWLINE+INDENT)

longStr = longStr.replace('}'+NEWLINE+','+NEWLINE , '},'+NEWLINE)

return longStr

elif isinstance(jsonNode, list):

longStr = '['+ NEWLINE

size = len(jsonNode)

for index in range(size):

item = jsonNode[index]

formattedItem = format(item, level + 1)

if index != size - 1:

# not yet the last one

longStr += (INDENT*level + formattedItem + ',' + NEWLINE)

else:

# the last one

longStr += (INDENT*level + formattedItem + NEWLINE)

longStr += INDENT * level + ']'+NEWLINE

return longStr

else:

if isinstance(jsonNode, unicode):

reprUnic = repr(jsonNode)

if reprUnic.startswith("u'") and reprUnic.endswith("'"):

return '\"' + reprUnic[2:-1].replace('"', "\\\"") + '\"'

elif reprUnic.startswith('u"') and reprUnic.endswith('"'):

return '\"' + reprUnic[2:-1].replace('"', "\\\"") + '\"'

if isinstance(jsonNode, str):

reprStr = repr(jsonNode)

if reprStr.startswith("'") and reprStr.endswith("'"):

return '\"' + reprStr[2:-1].replace('"', "\\\"") + '\"'

else:

return reprStr

elif jsonNode is None:

return "null"

elif jsonNode is True:

return "true"

elif jsonNode is False:

return "false"

return repr(jsonNode)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值