I am trying to remove elements from a json doc. Here's the input json.
{
"start": {
"docId": "3723",
"data": {
"dId": null,
"innerprops": {
"pId": "4573",
"stat": {
"statId": "7578",
"portaldata": [
{
"portalid": "67383",
"pairs": [
{
"id": "1111",
"loc": "denver"
},
{
"id": "2222",
"loc": "houston"
},
{
"id": "1111",
"loc": "austin"
},
{
"id": "3333",
"value": "miami"
}
],
"name": "popq"
}
]
},
"url": ""
}
}
}
}
I want to return json after removing the pairs from the 'pairs' property where the id is not equal to "1111". E.g. return value
{
"start": {
"docId": "3723",
"data": {
"dId": null,
"innerprops": {
"pId": "4573",
"stat": {
"statId": "7578",
"portaldata": [
{
"portalid": "67383",
"pairs": [
{
"id": "1111",
"loc": "denver"
},
{
"id": "1111",
"loc": "austin"
}
],
"name": "popq"
}
]
},
"url": ""
}
}
}
}
Here's my code
def main(req: func.HttpRequest) -> func.HttpResponse:
try:
data = req.get_json()
for entry in data["start"]["data"]["innerprops"]["stat"]["portaldata"]:
for pair in entry["pairs"]:
if pair["id"] != '1111':
del pair
except Exception as e:
logging.error(str(e))
return func.HttpResponse(str(e), status_code = 500)
return func.HttpResponse(str(data), status_code=200)
However the value is only deleted locally and the full document is being returned. What am I missing. Thanks.
CodePudding user response:
You can do with list comprehension,
for entry in data["start"]["data"]["innerprops"]["stat"]["portaldata"]:
entry["pairs"] = [pair for pair in entry["pairs"] if pair["id"] == '1111']
Result:
{'start': {'data': {'dId': None,
'innerprops': {'pId': '4573',
'stat': {'portaldata': [{'name': 'popq',
'pairs': [{'id': '1111',
'loc': 'denver'},
{'id': '1111',
'loc': 'austin'}],
'portalid': '67383'}],
'statId': '7578'},
'url': ''}},
'docId': '3723'}}