首页 > 解决方案 > 如何根据 Python 中键值的匹配从 JSON 文件中删除整个条目

问题描述

我有一个由一些软件输出的 JSON 文件,我希望根据type给定条目的 来分离 JSON 文件中的条目。JSON文件的结构是这样的:

{
  "Overall": [
    {
      "coeffs": [
        0.5,
        1.0
      ],
      "name": "LinearFit"
    }
  ],
  "Points": [
    {
      "coeffs": [
        -0.78,
        0.02
      ],
      "xvalue": "1995",
      "type": "DataPoint"
    },
    {
      "coeffs": [
        -0.54,
        0.00
      ],
      "xvalue": "1997",
      "type": "DataPoint"
    },
    {
      "coeffs": [
        -0.77,
        0.02
      ],
      "xvalue": "1998",
      "type": "InterpolatedData"
    },
    {
      "coeffs": [
        -0.66,
        0.23
      ],
      "xvalue": "1999",
      "type": "InterpolatedData"
    },
    {
      "coeffs": [
        -0.51,
        0.01
      ],
      "xvalue": "2000",
      "type": "DataPoint"
    }
  ]
}

我有下面的 Python 脚本,我一直在使用它来删除Pointswith中的所有条目type == InterpolatedData,但是在运行它时,并非所有情况都被删除。要清楚,我要写的输出应该是

{
  "Overall": [
    {
      "coeffs": [
        0.5,
        1.0
      ],
      "name": "LinearFit"
    }
  ],
  "Points": [
    {
      "coeffs": [
        -0.78,
        0.02
      ],
      "xvalue": "1995",
      "type": "DataPoint"
    },
    {
      "coeffs": [
        -0.54,
        0.00
      ],
      "xvalue": "1997",
      "type": "DataPoint"
    },
    {
      "coeffs": [
        -0.51,
        0.01
      ],
      "xvalue": "2000",
      "type": "DataPoint"
    }
  ]
}

这是我正在使用的代码(我在终端中使用 ArgumentParser,我想我会在问题中提到这一点,以防这可能是问题的原因):

import json
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter

def main(path):
    with open(path) as f:
        data = json.load(f)
    for entry in data['Points']:
        if entry['type']=='InterpolatedData':
            data['Points'].remove(entry)
    with open('./LinearFitUsingDataOnly.json', 'w') as f:
        json.dump(data,f)

if __name__ == "__main__":
    parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter)
    parser.add_argument("json", type=str, help="JSON file")
    args = parser.parse_args()
    main(args.json)

所以我会用命令在终端中运行它

$ python myPythonScript.py LinearFitAllPoints.json

我的输出不会删除 type 条目的所有实例InterpolatedData,只删除"xvalue": "1998"条目(即它遇到的第一个)。任何帮助将不胜感激,因为我无法理解为什么上面的代码没有删除所有案例(我也尝试过删除,给了我相同的结果)。

标签: pythonjson

解决方案


通过更换

for entry in data['Points']:

经过

for entry in list(data['Points']):

您创建条目的副本,而不是在删除时迭代它们,这通常是一个坏主意。


推荐阅读