如何从一个大的 json 文件中删除多个 json 对象

问题描述

大家好,我尝试了以下代码,最适合从 json 文件删除对象

#!/usr/bin/python

# Load the JSON module and use it to load your JSON file.
# I'm assuming that the JSON file contains a list of objects.
import json
obj  = json.load(open("pandas.json"))

# Iterate through the objects in the JSON and pop (remove)
# the obj once we find it.
for i in range(len(obj)):
    #path = ["000000000036.jpg","000000000049.jpg","000000000077.jpg"]
    if obj[i]["path"] == "000000000036.jpg":
        obj.pop(i)
        break

# Output the updated file with pretty JSON
open("updated_file.json","w").write(
    json.dumps(obj)
)

这里我有一个问题,如果我想从我尝试过但失败的 json 文件删除许多随机 json 对象,我应该怎么做,请让我清楚它“帮助欣赏”。

解决方法

假设 json 数据是一个 json 元素数组,下面的代码将从中删除 3 个随机元素。根据您的需要进行自定义。

import json
import random

data = json.load(open("filepath.json"))
print(json.dumps(data,indent=4))

keys_to_be_deleted = [random.randint(0,len(data)-1) for _ in range(3)]
[data.pop(i) for i in keys_to_be_deleted]
print(json.dumps(data,indent=4))
,
import json
obj = json.load(open("new_pandas.json"))

# Iterate through the objects in the JSON and pop (remove)
# the obj once we find it.
for i in range(len(obj)):
    path = ["000000000036.jpg","000000000049.jpg","000000000077.jpg"]

    for j in path:
        
        if obj[i]["path"] == j:
            obj.pop(i)
            break


# Output the updated file with pretty JSON
open("updated-file.json","w").write(
    json.dumps(obj)
)
,

我找到了如何从大 json 文件中删除特定 json 对象的方法,这是一个示例代码。

#!/usr/bin/python

# Load the JSON module and use it to load your JSON file.
# I'm assuming that the JSON file contains a list of objects.
import json
obj = json.load(open("new_pandas.json"))

# Iterate through the objects in the JSON and pop (remove)
# the obj once we find it.

num = 0
n = 0
flag = False

for i in range(len(obj)):
    path = ["000000170035.jpg","000000171962.jpg","000000004972.jpg"]

    for j in path:

        if obj[n]["path"] == j:
            print(obj[n]["path"])
            obj.pop(n)
            flag = True
            break

    if flag == False: # Cannot find pass forward 
        n = n + 1
    else:
        flag = False


    if obj[i]["path"] == "000000581357.jpg": #end object of json file
        break

    # print(obj[i]["path"])
    num = num + 1
    if num >= 100000:
        break

# Output the updated file with pretty JSON
open("updated-file.json","w").write(
    json.dumps(obj)
)