【问题标题】:how to remove duplicate JSON object in python如何在python中删除重复的JSON对象
【发布时间】:2019-08-08 12:09:26
【问题描述】:

我想从 JSON 文件中删除包含重复 'file_url' 的对象。像这样。

{
    "0": {
        "file_url": "apple",
        "name": "apple.jpg"
    },
    "1": {
        "file_url": "dog",
        "name": "dog.jpg"
    },
    "2": {
        "file_url": "apple",
        "name": "apple.jpg"
    },
    "3": {
        "file_url": "cat",
        "name": "cat.jpg"
    },
    "4": {
        "file_url": "tiger",
        "name": "tiger.jpg"
    }
}

这是我的 json 文件。和数字 0 和 2 是相同的东西。所以,我想删除其中一个并用新索引对其进行排序。像这样:

{
    "0": {
        "file_url": "apple",
        "name": "apple.jpg"
    },
    "1": {
        "file_url": "dog",
        "name": "dog.jpg"
    },
    "2": {
        "file_url": "cat",
        "name": "cat.jpg"
    },
    "3": {
        "file_url": "tiger",
        "name": "tiger.jpg"
    }
}

我查了几份文件,但没有用。我正在使用 Python 3.6,我需要帮助。

【问题讨论】:

    标签: json python-3.x duplicates


    【解决方案1】:

    这可能效率不高,但您可以对照第一个数组的每个元素检查第二个数组的每个元素。每次你得到 element[i]==element[x] 时,你都会从你想要的任何对象中删除副本。

    编辑:很抱歉没有实际发布任何代码 你可能想要一个像这样的嵌套循环......

     for i in object1:
       for x in object2:
      *check and delete if needed here*
    

    我是堆栈溢出的新手,很难正确缩进:p

    额外编辑:我真的只是略过了您的问题,并没有意识到您只处理一个对象。我想也许你有两个对象,但是如果你复制原始对象,这种方法可能会起作用

    【讨论】:

    • 这一定比我想象的更难。谢谢您的考虑! :)
    猜你喜欢
    • 2014-08-23
    • 2016-03-01
    • 1970-01-01
    • 2013-10-12
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    相关资源
    最近更新 更多