简体   繁体   English

Python 从一个 json 文件中减去 json 对象(如果它们出现在另一个 Z466DEEC76ECDF5FCA6D38571F6324Z 文件中)

[英]Python subtract json objects from one json file if they occur in another json file

I'd like to be able to remove objects from one json file if they contain a key:value pair that matches another json file.如果对象包含与另一个 json 文件匹配的键:值对,我希望能够从一个 json 文件中删除对象。

File1:文件1:

[
  {
    "Admin": "aaa",
    "id": "111",
    "osType": "Windows",
    "publicIps": [],
    "resourceGroup": "bbb",
    "vmName": "example1"
  },
  {
    "Admin": "aaa",
    "id": "222",
    "osType": "Windows",
    "publicIps": [],
    "resourceGroup": "bbb",
    "vmName": "example2"
  },
  {
    "Admin": "aaa",
    "id": "333",
    "osType": "Windows",
    "publicIps": [],
    "resourceGroup": "bbb",
    "vmName": "example3"
  },
  {
    "Admin": "aaa",
    "id": "444",
    "osType": "Windows",
    "publicIps": [],
    "resourceGroup": "bbb",
    "vmName": "example4"
  },
]

File2:文件2:

[
 [
  {
   "vmName": "example1"
  }
 ],
 [
  {
   "vmName": "example2"
  }
 ],
 [
  {
   "vmName": "example3"
  }
 ],
]

Desired result in file3(or modified file1):文件3(或修改后的文件1)中的所需结果:

[
  {
    "Admin": "aaa",
    "id": "444",
    "osType": "Windows",
    "publicIps": [],
    "resourceGroup": "bbb",
    "vmName": "example4"
  },
]

I have found a few ways to remove elements from my first file, but I want to remove the entire object based on if it's k:v matches the any k:v in file2, I'm unaware of any way to do that.我找到了一些从我的第一个文件中删除元素的方法,但我想删除整个 object,基于它的 k:v 是否与 file2 中的任何 k:v 匹配,我不知道有任何方法可以做到这一点。

Solution:解决方案:

def return_non_repetitive_records(file1, file2):
    result = file1.copy()
    for i in range(len(file2)):
        for j in range(len(result)):
            if result[j]['vmName'] == file2[i][0]['vmName']:
                result.pop(j)
                break
    return result

Usage:用法:

file3 = return_non_repetitive_records(file1, file2)

Result:结果:

[{'Admin': 'aaa',
  'id': '444',
  'osType': 'Windows',
  'publicIps': [],
  'resourceGroup': 'bbb',
  'vmName': 'example4'}]

The Data You Provided:您提供的数据:

file1 = [
  {
    "Admin": "aaa",
    "id": "111",
    "osType": "Windows",
    "publicIps": [],
    "resourceGroup": "bbb",
    "vmName": "example1"
  },
  {
    "Admin": "aaa",
    "id": "222",
    "osType": "Windows",
    "publicIps": [],
    "resourceGroup": "bbb",
    "vmName": "example2"
  },
  {
    "Admin": "aaa",
    "id": "333",
    "osType": "Windows",
    "publicIps": [],
    "resourceGroup": "bbb",
    "vmName": "example3"
  },
  {
    "Admin": "aaa",
    "id": "444",
    "osType": "Windows",
    "publicIps": [],
    "resourceGroup": "bbb",
    "vmName": "example4"
  },
]


file2 = [
 [
  {
   "vmName": "example1"
  }
 ],
 [
  {
   "vmName": "example2"
  }
 ],
 [
  {
   "vmName": "example3"
  }
 ],
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM