烧瓶json响应最后一个元素

时间:2017-12-02 19:40:14

标签: python json flask

假设我有json文件,如下所示:

{
  "task": [
    {
      "description": "Milk, Cheese, Pizza, Fruit, Tylenol", 
      "done": False, 
      "id": 1, 
      "title": "Buy groceries"
    }, 
    {
      "description": "Need to find a good Python tutorial on the web", 
      "done": False, 
      "id": 2, 
      "title": "Learn Python"
    }
  ]
}

我想知道如何访问json响应中的最后一个元素。我已尝试使用下面的代码进行递增,但它不起作用:

id': request.json['task'][-1]['id'] + 1 

1 个答案:

答案 0 :(得分:1)

如果你想增加id两个,你可以这样做:

d = {
  "task": [
   {
      "description": "Milk, Cheese, Pizza, Fruit, Tylenol", 
      "done": False, 
      "id": 1, 
      "title": "Buy groceries"
   }, 
   {
    "description": "Need to find a good Python tutorial on the web", 
    "done": False, 
    "id": 2, 
    "title": "Learn Python"
  }
 ]
}
new_d = {"task":[{a:b+1 if a == "id" else b for a, b in i.items()} for i in d['task']]}

输出:

{'task': [{'id': 2, 'done': False, 'description': 'Milk, Cheese, Pizza, Fruit, Tylenol', 'title': 'Buy groceries'}, {'id': 3, 'done': False, 'description': 'Need to find a good Python tutorial on the web', 'title': 'Learn Python'}]}

如果要增加列表中最后一个字典中存在的id

d['task'][-1]['id'] += 1