烧瓶JSON响应最后一个元素

比方说,我有JSON文件如下:烧瓶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 

回答:

如果你想同时增加id S,你可以这样做:

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 

以上是 烧瓶JSON响应最后一个元素 的全部内容, 来源链接: utcz.com/qa/257975.html

回到顶部