Python Json数据排序

import hashlib


# recursively calculate each element block's hashcode, and reorder the child nodes in the list basing on the hashcode
# finally will get the ordered json object and overall hashcode
def ordered(jsonNode):
    if isinstance(jsonNode, dict):
        # object node
        for key in jsonNode.keys():
            value = jsonNode[key]
            sortedValue, hashCode = ordered(value)
            # hashCode is not used here, python reorder a dict by their keys defaultly
            jsonNode[key] = sortedValue
        return jsonNode, hashlib.sha256(repr(jsonNode)).hexdigest()
    elif isinstance(jsonNode, list):
        # list node
        itemWithHash = {}
        hashConflictCount = {}
        for item in jsonNode:
            newItem, hashCode = ordered(item)
            if hashCode in itemWithHash.keys():
                # repeating nodes in this list, count + 1
                hashConflictCount[hashCode] += 1
            else:
                # new node to add, first time see it
                itemWithHash[hashCode] = newItem
                hashConflictCount[hashCode] = 1
        # sort nodes in the list by their hash code
        sortedHash = sorted(itemWithHash.keys())

        # reconstruct the whole list basing on the order of their node hash codes
        newList = []
        for key in sortedHash:
            count = hashConflictCount[key]
            for i in range(count):
                newList.append(itemWithHash[key])
        return newList, hashlib.sha256(repr(newList)).hexdigest()
    else:
        # simple data type node. Either list's element or object's value part in key-value pair
        return jsonNode, hashlib.sha256(repr(jsonNode)).hexdigest()


重新格式化:
# 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)

  

 

转载于:https://www.cnblogs.com/hylinux/p/8295140.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值