比较两个json对象并删除该元素,然后将结果json与其他json文件进行比较

时间:2017-05-27 01:09:49

标签: python json parsing dictionary

Python新手:

Default.json

   {
"name": {
 "provide": ""
},
"test": {
  "Fail": {
    "centers": None,
    "Nearest": 0
  },
  "far": "",
  "Meta": null,
  "Only": false,
  "Tags": null
 },
"Session": "",
"conf": {
  "check": "",
  "Reg": ""
 },
"Token": "" 

}

Remote.json

 [ {
  'name': {
  'provide': ''
   },
  'Name': 'abc',
  'test': {
    'Service': 'redis',
    'Tags': [
      'stage'
     ],
    'Fail': {
      'centers': None,
      'Nearest': 3
     },
     'Only': false,
     'far': '',
     'Meta': null
    },
   'Token': '',
   'Session': '',

   'conf': {
     'Reg': '',
     'check': 'name_prefix_match'
    },
} ]

我有一个 default.json 远程.json 。我试图实现的是从<删除所有json元素 strong> remote.json , remote.json 的值与 default.json 匹配。例如,因为键,名称的值: default.json 中的{provider =“”} remote.json 中的名称:{provider =“”} 相匹配它应该从 remote.json

中删除
with open(remote.json) as f:
 with open(default.json) as m:
   file=json.load(f)
   default=json.load(m)
   for i in xrange(len(file)):
     for key,value in default.items():
        #default[key]=value
      #a=filter(lambda x: x[""],file.keys())

1.我不知道如何从默认获取密钥,值并将其与文件进行比较?任何帮助都将不胜感激。

我需要从remote.json中删除元素的原因是因为我需要将结果json与其他json文件“local.json”进行比较。如果我没有'删除键,值为“”的值为null或null或None那么remote.json和local.json之间的比较将永远不会相等。

2.有没有更好的方法来解决这个问题?

local.json

{ 
  "Name": "",
  "conf": {
   "check": "name_prefix_match",
  },
  "test": {
    "Service": "redis",
    "Fail": {
     "Near": 3
   },
  "Tags": ""
  }
}

1 个答案:

答案 0 :(得分:2)

JSON示例存在一些问题,原因是None&amp; False不是有效的JSON对象(single-quoted string literals也是如此),所以让我们假装我们已经解析过文件并得到像

这样的文件。
default_json = {
    "name": {
        "provide": ""
    },
    "test": {
        "Fail": {
            "centers": None,
            "Nearest": 0
        },
        "far": "",
        "Meta": None,
        "Only": False,
        "Tags": None
    },
    "Session": "",
    "conf": {
        "check": "",
        "Reg": ""
    },
    "Token": ""
}

remote_json = [{
    "name": {
        "provide": ""
    },
    "Name": "abc",
    "test": {
        "Service": "redis",
        "Tags": [
            "stage"
        ],
        "Fail": {
            "centers": None,
            "Nearest": 3
        },
        "Only": False,
        "far": "",
        "Meta": None
    },
    "Token": "",
    "Session": "",

    "conf": {
        "Reg": "",
        "check": "name_prefix_match"
    },
}]

假设remote.json是词典列表&amp;应使用default.json

过滤掉其中的每一个
filtered_remote_json = [dict(item
                             for item in dictionary.items()
                             if item not in default_json.items())
                        for dictionary in remote_json]

会给我们

filtered_remote_json == [{"Name": "abc",
                          "test": {"Service": "redis", "Tags": ["stage"],
                                   "Fail": {"centers": None,
                                            "Nearest": 3}, "Only": False,
                                   "far": "", "Meta": None},
                          "conf": {"Reg": "",
                                   "check": "name_prefix_match"}}]

修改

如果我们还需要过滤子词典,那么接下来有点讨厌的效用函数应该有帮助

def filter_defaults(json_object, default_json_object):
    result = {}
    for key, value in json_object.items():
        try:
            default_value = default_json_object[key]
        except KeyError:
            # key not in defaults, adding to result
            result[key] = value
            continue

        # we need to process sub-dictionaries as well
        if isinstance(value, dict):
            value = filter_defaults(value, default_value)
            # we are not interested in empty filtered sub-dictionaries
            if not value:
                continue
        # value should differ from default
        elif value == default_value:
            continue

        result[key] = value

    return result

然后写下

filtered_remote_json = [filter_defaults(dictionary, default_json)
                        for dictionary in remote_json]

这会给我们

filtered_remote_json == [{"Name": "abc",
                          "test": {"Service": "redis", "Tags": ["stage"],
                                   "Fail": {"Nearest": 3}},
                          "conf": {"check": "name_prefix_match"}}]