2017-12-02 174 views
0

比方說,我有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 
+0

你想要的輸出是什麼? – Ajax1234

+0

我想在代碼中自動incerement id。我的意思是,無論前端會在這裏返回,它必須每次增加 – human

+0

'request.json ['task'] [ - 1] ['id'] + = 1'你的意思是? – Arman

回答

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 
+0

謝謝你的迴應。但問題是實際的文件很大,這只是一個例子。在我的情況下,我有json文件,每個請求都必須增加id – human