JSON删除不包含的对象

lnvxswe2  于 2023-01-27  发布在  其他
关注(0)|答案(1)|浏览(170)

我处理JSON数据并希望删除不必要的对象。“message”键不包含的对象 [“vente”或“sell”或“achat”或“buy”和“zonedentr”] OR [“pipsclture”或“pipsclture”或“pipclture”或“pipclture”] OR [“fermer le trade”或“fermez le trade”] OR [“modifier sl”]
下面是我带来的代码:

import json

# Load the JSON data
with open("Telegram_Msg.json", "r") as file:
    data_dict = json.load(file)

# Filter out unnecessary objects
data_dict = [d for d in data_dict if "message" in d and (
    (("vente" in d["message"] or "sell" in d["message"] or "achat" in d["message"] or "buy" in d["message"]) and "zonedentr" in d["message"]) or
    ("pipsclture" in d["message"] or "pipscloture" in d["message"] or "pipclture" in d["message"] or "pipcloture" in d["message"]) or
    ("fermer le trade" in d["message"] or "fermez le trade" in d["message"]) or
    "modifier sl" in d["message"]
)]

# Reorganize the data
# ...

# Export data to new JSON file
with open('output.json', 'w') as f:
    json.dump(data_dict, f, indent=4)

但这并不奏效,它不是删除不包含特定文本的不必要对象,而是删除output.json文件为空的所有内容......

rkue9o1l

rkue9o1l1#

最好将所有不必要的值放在一个列表中,并使用all过滤它们:

to_remove = [
    "vente", "sell", "achat", "buy", "zonedentr",
    "pipsclture", "pipscloture", "pipclture", "pipcloture",
    "fermer le trade", "fermez le trade",
    "modifier sl"
]

data_dict = [
    d for d in data_dict 
    if "message" not in d or all(r not in d['message'] for r in to_remove)
]

相关问题