在 JSON 中查找长于​​ X 的行并删除整个对象

在 JSON 中查找长于​​ X 的行并删除整个对象

我有一个巨大的 JSON 数组,其中包含数千个对象,我需要过滤文本字段太长(例如 200 个字符)的所有对象。

我发现了很多 SED/AWK 建议来查找具有一定长度的行,但是如何删除该行及其前面的 1 和后面的 2;这样整个 JSON 对象就被删除了?

结构如下:

{ "text": "blah blah blah", "author": "John Doe" }

谢谢!

答案1

这是一个可以执行您想要的操作的 Python 脚本:

#!/usr/bin/env python
# -*- coding: ascii -*-
"""filter.py"""

import sys

# Get the file and the maximum line-length as command-line arguments
filepath = sys.argv[1]
maxlen = int(sys.argv[2])

# Initialize a list to store the unfiltered lines
lines = []

# Read the data file line-by-line
jsonfile = open(filepath, 'r')
for line in jsonfile:

    # Only consider non-empty lines
    if line:

        # For "text" lines that are too line, remove the previous line
        # and also skip the next two line
        if "text" in line and len(line) > maxlen: 
            lines.pop()
            next(jsonfile)
            next(jsonfile)
        # Add all other lines to the list
        else:
            lines.append(line)

# Strip trailing comma from the last object
lines[-2] = lines[-2].replace(',', '')

# Output the lines from the list
for line in lines:
    sys.stdout.write(line)

你可以这样运行它:

python filter.py data.json 34

假设您有以下数据文件:

[
    {
    "text": "blah blah blah one",
    "author": "John Doe"
    },
    {
    "text": "blah blah blah two",
    "author": "John Doe"
    },
    {
    "text": "blah blah blah three",
    "author": "John Doe"
    }
]

然后按照描述运行脚本将产生以下输出:

[
    {
    "text": "blah blah blah one",
    "author": "John Doe"
    },
    {
    "text": "blah blah blah two",
    "author": "John Doe"
    }
]

相关内容