比较Python中的两个Json树

时间:2017-02-22 08:34:20

标签: python json

我有这种Json树用于文件夹结构。有没有办法将它与相同类型的Json树进行比较以获得差异(文件丢失或不同的文件属性(date,crc,..))并将其作为包含不同/缺失文件名称的列表返回。

{
      "testfolder": {
        "children": {
          "content.json": {
            "last_modified_timestamp": 1485902084.0222416, 
            "created_timestamp": 1485193414.5027652, 
            "crc": "7c71cf7ff765ddd78fffcac2eed56ae2", 
            "type": "file", 
            "size": 961
          }, 
          "config.json": {
            "last_modified_timestamp": 1484831126.4821935, 
            "created_timestamp": 1484830625.6165457, 
            "crc": "bff5d42e18df483841aa10df8b38cdd4", 
            "type": "file", 
            "size": 132
          }
        }
      },  
      "__init__.py": {
        "last_modified_timestamp": 1481651800.7150106, 
        "created_timestamp": 1481651800.7150106, 
        "crc": "d41d8cd98f00b204e9800998ecf8427e", 
        "type": "file", 
        "size": 0
      }, 
      "test.json": {
        "last_modified_timestamp": 1486126931.2528062, 
        "created_timestamp": 1486126732.7074502, 
        "crc": "8a30d9b3834ef46ad3b996edb06c72bf", 
        "type": "file", 
        "size": 1675
      }, 
      "test": {
        "children": {
          "test.txt.txt": {
            "last_modified_timestamp": 1486126927.9266162, 
            "created_timestamp": 1486126865.9750726, 
            "crc": "b5301fdbf2ba41520b255a651c7017b1", 
            "type": "file", 
            "size": 5
          }
        }
      }
    }

谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

def jsondiff(local,online,path='',todo=[]):
  for key in local.keys():
      if not online.has_key(key):
          if local[key].has_key('children'):
              todo = todo + json_path_print(local[key]["children"],path+key+"/")
          else:
              todo.append(path+key)
      else:
          if local[key].has_key('children'):
              todo=todo+jsondiff(local[key]["children"],online[key]["children"],path+key+"/")
          else:
              if local[key]["last_modified_timestamp"]>online[key]["last_modified_timestamp"]:
                  todo.append(path + key)
  return todo

解决了它,如果有人需要解决方案