JSONでXより長い行を見つけて、オブジェクト全体を削除します。

JSONでXより長い行を見つけて、オブジェクト全体を削除します。

何千ものオブジェクトを含む巨大なJSON配列があり、テキストフィールドが長すぎる(たとえば200文字)、すべてのオブジェクトをフィルタリングする必要があります。

特定の長さの行を見つけるための多くのSED / AWK提案を見つけましたが、JSONオブジェクト全体が削除されるように、行とその前の1、後の2をどのように削除しますか?

構造は次のとおりです。

{ "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"
    }
]

おすすめ記事