【问题标题】:Remove specific data from json file in linux从linux中的json文件中删除特定数据
【发布时间】:2021-09-03 02:55:22
【问题描述】:

我有一个带有重复字段的数据集的 json 文件。我需要删除包含特定字段数据的条目。

Json 文件:

[
    {
        "targets": [
            "172.17.1.199"
        ],
        "labels": {
            "__meta_netbox_pop": "st-1742",
            "__snmp_module__": "arista_sw"
        }
    },
    {
        "targets": [
            "172.17.1.51"
        ],
        "labels": {
            "__meta_netbox_pop": "st-1754",
            "__snmp_module__": "arista_sw"
        }
    }
]

json 文件继续,但这是整个 json 文件的示例。

在给定target's IP 数据的情况下,我需要删除targets 及其labels 的条目。

输入:

172.17.1.51

预期输出:

[
    {
        "targets": [
            "172.17.1.199"
        ],
        "labels": {
            "__meta_netbox_pop": "st-1742",
            "__snmp_module__": "arista_sw"
        }
    }
]

【问题讨论】:

    标签: python linux jq centos7


    【解决方案1】:

    使用jq:

    $ jq --arg ip 172.17.1.51 'map(select(.targets | contains([$ip]) | not ))' input.json 
    [
      {
        "targets": [
          "172.17.1.199"
        ],
        "labels": {
          "__meta_netbox_pop": "st-1742",
          "__snmp_module__": "arista_sw"
        }
      }
    ]
    

    【讨论】:

    • 我怎样才能让它接受标签.__meta_netbox_pop?说st-1754?输出应该还是一样的
    • 好的,想通了。使用jq --arg store 'st-3829' 'map(select(.labels.__meta_netbox_pop | contains($store) | not ))' test.json > output.json
    • @user13539846 map(select(.labels.__meta_netbox_pop != $store))
    【解决方案2】:

    如果我正确理解了这个问题,这应该可以解决问题:

    target参数是要移除的IP地址,file_path是json文件的路径

    编辑:另外,不要忘记import json,否则它不会工作

    def remove_obj(target, file_path):
        with open(file_path, "r") as data_file:
            data = json.load(data_file)
    
        for obj in data:
            if target in obj["targets"]:
                data.remove(obj)
    
        with open(file_path, "w") as data_file:
            json.dump(data, data_file, indent=4)
    

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 2021-12-22
      • 1970-01-01
      • 2021-04-15
      • 2015-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-30
      相关资源
      最近更新 更多