博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python Json数据排序
阅读量:6279 次
发布时间:2019-06-22

本文共 4400 字,大约阅读时间需要 14 分钟。

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 hashcodedef 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

你可能感兴趣的文章
IGRP中的RTP、Neighbor Discovery协议及Time总结
查看>>
Silverlight C# 游戏开发:Flyer09扇动翅膀的蝴蝶
查看>>
Linux超级杯:7步让你换个新内核
查看>>
Memcached实战之单机部署----单实例/多实例
查看>>
搭建NTP时间服务器
查看>>
城域网国干BGP路由宣告
查看>>
thrift的使用—servlet服务器端与as3客户端通信
查看>>
Spring集成ActiveMQ
查看>>
理解 Keystone 核心概念 - 每天5分钟玩转 OpenStack(18)
查看>>
NP系列三十六--利用ODR实现公司总部和分支机构的通讯
查看>>
遭遇ARP欺骗
查看>>
【移动开发】Android中一些你可能不太知道的东西
查看>>
MongoDB mapReduce案例分析一
查看>>
asp.net 关于提示“当前上下文中不存在名称"XXX"”的一种情况的解决办法
查看>>
MOSS系列二 创建第一个SharePoint站点
查看>>
Detach Volume 操作 - 每天5分钟玩转 OpenStack(55)
查看>>
MySQL5.6 部署MHA
查看>>
DG配置网络,报ORA-12514: TNS:listener does not...
查看>>
hadoop开启webHDFS服务及测试
查看>>
DC学院学习笔记(十七):分类及逻辑回归
查看>>