删除 JSON 数据,如果在主要 json 数据中可用

Delete JSON data, if available in main json data

我有两个json数据,其中json_main和json1如下所示。我想检查 json1,如果 json_main 数据中有任何详细信息,则应删除确切的详细信息和预期结果,我看起来像下面显示的“结果 Result_json”。

例如:在 json1 数据“”字段”中:{ "完整地址": "data2", “赫兹”:“文本2”, "ot": "doc2"" 在 json_main 数据中可用。所以我想从 json1 数据中删除它。

我尝试使用 python 代码,但我不知道如何与 json_main 数据进行比较并删除 json1 数据。

json_main

 [
  {
    "fields": {
      "Full Address": "data1",
      "hz": "text1",
      "ot": "doc1"
   }
  },
  {
  "fields": {
    "Full Address": "data2",
    "hz": "text2",
    "ot": "doc2"
     }
   }
   ]

json1

 [
  {
    "fields": {
      "Full Address": "data2",
      "hz": "text2",
      "ot": "doc2"
   }
  },
  {
  "fields": {
    "Full Address": "data3",
    "hz": "text3",
    "ot": "doc3"
  }
 }
 ]

结果Result_json

 [
  {
  "fields": {
    "Full Address": "data3",
    "hz": "text3",
    "ot": "doc3"
  }
 }
 ]

Python

  with open('writing_file.json', 'w') as w:
  with open('reading_file.json', 'r') as r:
    for line in r:
        element = json.loads(line.strip())
        if 'data2' in element:
            del element['data2']
        w.write(json.dumps(element))

我想回答我自己的问题。首先,我将从“json_main”生成“完整地址”的值作为唯一键,即“data1”、“data2”。

unique_key = ["data1", "data2"]

正在过滤“json1”的数据。请参阅下面的 python 代码。

python代码

  import json
  import sys
  
  unique_key = [elt["fields"]["Full Address"] for elt in json_main]
  print( unique key)
  Output =  ["data1", "data2"]


  json1 = [
        {
      "fields": {
           "Full Address": "data2",
           "hz": "text2",
           "ot": "doc2"
          }
          },
         {
     "fields": {
           "Full Address": "data3",
           "hz": "text3",
           "ot": "doc3"
               }
               }
             ]


 #  delete json objects.
 data2 = [x for x in json1 if x['fields']['Full Address'] not in unique_key]

 print(data2)

  data2 = [
          {
       "fields": {
           "Full Address": "data3",
           "hz": "text3",
           "ot": "doc3"
                 }
                }
             ]