在python中根据条件值过滤JSON数组

问题描述 投票:0回答:1

我正在努力过滤一个巨大的 JSON 文件。数据呈现为:

{
    'network': '2a0d:4bc0::/29',
    'metric': 100,
    'primary': true,
    'id':'2a0d: 4bc0::/29',
    'bgp':{
        'origin': 'IGP',
        'ext_communities': [],
        'large_communities': [
            [6695, 1000, 1],
            [6695, 1902, 9009]
        ],
        'med': 0,
        'as_path': [34549, 3214],
        'next_hop': '2001:7f8:a0::86f5:0:1fe80::42de:ad03:61d1:efe4',
        'communities':[
            [0, 6939],
            [0, 9009],
            [0, 32934],
            [0, 48793],
            [0, 57344],
            [3214, 200],
            [6695, 9145],
            [34549, 100],
            [34549, 300],
            [65212, 11000],
            [65101, 1001],
            [65102, 1000],
            [65103, 276],
            [65104, 150]
        ],
        'local_pref': 100
    }
}
>>> with gzip.open(file, 'rt') as f:
  ....data = json.load(f)

我可以使用不同的键通过如下编码来访问数据:

>>> for i in data: 
   ...for element in data[i][exported]:
   .....print(element['bgp']['communities'], element['bgp']['large_communities'])

我有以下输出:

[
    [0, 12989],
    [0, 13335],
    [0, 15133],
    [0, 15169],
    [0, 16509],
    [0, 20940],
    [0, 22822],
    [0, 2906],
    [0, 32590],
    [0, 48641],
    [0, 49029],
    [0, 714],
    [65101, 11077],
    [65102, 11000],
    [65103, 724],
    [65104, 150]
]

我想要的是过滤以“0”开头的值,例如

[0, 9009], [0, 48793]....
,输出可能如下所示:

[
    [0, 12989],
    [0, 13335],
    [0, 15133],
    [0, 15169],
    [0, 16509],
    [0, 20940],
    [0, 22822],
    [0, 2906],
    [0, 32590],
    [0, 48641],
    [0, 49029],
    [0, 714]
]

或以

65101

开头的

我不知道该使用哪种过滤方法。

python arrays json filter conditional-statements
1个回答
1
投票

试试这个

# Load your data
data = None
with open(file, 'r') as file:
    data = json.loads(file.read())

# Load communities field, filter on values with 0 or 65101 in the first column
communities = data['bgp']['communities']
result = list(filter(lambda x: x[0] == 0 or x[0] == 65101, communities))

© www.soinside.com 2019 - 2024. All rights reserved.