Удалить атрибут по его ключу из массива jsonb в цикле

Посмотрите на этот код:

import PyPDF2
pdf_file = open('sample.pdf', 'rb')
read_pdf = PyPDF2.PdfFileReader(pdf_file)
number_of_pages = read_pdf.getNumPages()
page = read_pdf.getPage(0)
page_content = page.extractText()
print page_content.encode('utf-8')

Выход:

!"#$%#$%&%$&'()*%+,-%./01'*23%4
5'%1$#26%3/%7/))/8%&)/26%8#3"%3"*%313/9#&)
%

Используя тот же код для чтения pdf из 201308FCR.pdf . Выход нормальный.

Его документация объясняет, почему:

def extractText(self):
    """
    Locate all text drawing commands, in the order they are provided in the
    content stream, and extract the text.  This works well for some PDF
    files, but poorly for others, depending on the generator used.  This will
    be refined in the future.  Do not rely on the order of text coming out of
    this function, as it will change if this function is made more
    sophisticated.
    :return: a unicode string object.
    """

1
задан klin 15 January 2019 в 19:20
поделиться

1 ответ

Вы можете изменить только один элемент массива на каждом шаге цикла, поэтому вам нужно использовать новую переменную для агрегирования результатов:

do $
declare 
    groups jsonb = 
    '[
        {"id": "1", "name": "Ann", "age": 20 },
        {"id": "2", "name": "Margaret", "age": 30 }
    ]';
    new_groups jsonb = '[]';
begin
    for i in 0..jsonb_array_length(groups) - 1
    loop
        new_groups:= new_groups || (groups->i) - 'age';
    end loop;
    raise notice '%', new_groups;
end $;

NOTICE:  [{"id": "1", "name": "Ann"}, {"id": "2", "name": "Margaret"}]
DO

Лучше сделать то же самое в один запрос без цикла и дополнительной переменной:

do $
declare 
    groups jsonb = 
    '[
        {"id": "1", "name": "Ann", "age": 20 },
        {"id": "2", "name": "Margaret", "age": 30 }
    ]';
begin
    select jsonb_agg(value- 'age')
    from jsonb_array_elements(groups)
    into groups;
    raise notice '%', groups;
end $;
0
ответ дан klin 15 January 2019 в 19:20
поделиться
Другие вопросы по тегам:

Похожие вопросы: