2017-02-22 288 views
-1

我有这种JSON树的文件夹结构。有什么方法可以将它与同类的Json树进行比较以获得差异(文件丢失或不同的文件属性(日期,crc,..)),并将其作为具有不同/缺失文件名称的列表返回。比较Python中的两个JSON树

{ 
     "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 
      } 
     } 
     } 
    } 

谢谢你的帮忙!

+0

那么你尝试过这么远吗? –

+1

加载在字典中,然后使用比较字典,就像那一个无数的答案:http://stackoverflow.com/questions/4527942/comparing-two-dictionaries-in-python –

+0

我已经尝试过递归返回列表具有完整路径的文件而不仅仅是两个列表之间的区别,但是这只解决了缺失文件而不是不同文件。 – Slajc

回答

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 

解决它,如果有人需要解决