localize linhas maiores que X em JSON e exclua todo o objeto

2

Eu tenho um enorme JSON Array com vários mil objetos e preciso filtrar todos os objetos onde o campo de texto é muito longo (digamos 200 caracteres).

Eu encontrei muitos conselhos SED / AWK para encontrar uma linha com um certo tamanho, mas como posso deletar essa linha E o 1 antes e o 2 depois dele; para que todo o objeto JSON seja excluído?

A estrutura é como segue:

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

Obrigado!

    
por ChrisNix 23.05.2018 / 23:37

1 resposta

0

Aqui está um script Python que faz o que você quer:

#!/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)

Você pode executá-lo assim:

python filter.py data.json 34

Suponha que você tenha o seguinte arquivo de dados:

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

Em seguida, a execução do script conforme descrito produziria a seguinte saída:

[
    {
    "text": "blah blah blah one",
    "author": "John Doe"
    },
    {
    "text": "blah blah blah two",
    "author": "John Doe"
    }
]
    
por 23.05.2018 / 23:59