【问题标题】:Delete JSON data, if available in main json data删除 JSON 数据(如果在主 json 数据中可用)
【发布时间】:2021-03-15 15:31:50
【问题描述】:

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

例如:在json1数据""fields"中:{ "完整地址": "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))

【问题讨论】:

  • 如果只有一个字段相同怎么办?你为什么要明确检查'data2'
  • 然后结果在 json 正文中没有给出任何内容。

标签: python json delete-operator


【解决方案1】:

我想回答我自己的问题。首先,我将从“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"
                 }
                }
             ]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 2017-12-14
    • 2013-11-23
    • 2018-05-31
    • 2021-05-08
    • 1970-01-01
    相关资源
    最近更新 更多