首页 > 解决方案 > 如何删除某些东西 json 列表?

问题描述

我有这个显示文章的程序,我想添加一个删除文章的选项。底部代码是添加或编辑现有文章内容的选项。我想知道是否使用部分代码来查看是否存在标题以从列表中删除文章。json 列表包含两个对象:标题和内容。因此,在删除标题时,我还想删除其内容。

import json
from bottle import route, run, template, request, redirect, static_file, error

@route('/remove')

    articles = read_articles_from_file()

    title = getattr(request.forms, "title")
    
    append_flag = True
    for i, article in enumerate(articles):     #loop through existing articles
        if title == article['title']:          #if title exists in articles                  
@route('/update', method="POST")
def update_article():
    """
    Receives page title and contents from a form, and creates/updates a
    text file for that page.
    """

    title = getattr(request.forms, "title")
    content = getattr(request.forms, "content")

    articles = read_articles_from_file()

    append_flag = True
    for i, article in enumerate(articles):      #loop through existing articles
        if title == article['title']:           #if new title already exists
            articles[i]['content'] = content    #update articles content
            append_flag = False                 #update flag to false
            break                               #if title is unique, break loop 

    if append_flag:                             #add new post
        articles.append({
            "title": title.strip(),              
            "content": content
        })


    my_file = open("storage/articles.json", "w")
    my_file.write(json.dumps(articles, indent=3))
    my_file.close()

标签: python

解决方案


首先找到项目。然后使用list.pop list docs删除它。像这样:

>>> articles = [{'title': 'one', 'content': 'content_one'}, {'title': 'two', 'content': 'content_two'}]
>>> articles
[{'title': 'one', 'content': 'content_one'}, {'title': 'two', 'content': 'content_two'}]
>>> title_to_remove = 'one'
>>> matching_index = next(i for i, a in enumerate(articles) if a['title'] == title_to_remove)
>>> matching_index
0
>>> articles.pop(matching_index)
{'title': 'one', 'content': 'content_one'}
>>> articles
[{'title': 'two', 'content': 'content_two'}]

推荐阅读