I have following json file:
[{
"subject": "Test AAA",
"id": "1234",
"LineItems": [
{
"parent_id": "",
"productid": "24x34147",
"sequence-no": "1",
"quantity": "0.000",
"listprice": 0.0
},
{
"parent_id": "",
"productid": "24x34147",
"sequence-no": "2",
"quantity": "5.000",
"listprice": 0.0
}
]
}]
I am trying to delete the dictionary/dictionaries inside of the LineItems which have quantity = "0.000" and save the other data as it is in the same format. Following is my code and what I have tried. It is printing an empty list.
with open("examplejson.json", 'r') as f:
data = json.loads(f.read())
for element in data:
service_id = element["LineItems"]
for i, el in enumerate(service_id):
# print(service_id[i]["quantity"])
a = [item for item in el if service_id[i]["quantity"] == "0.000"]
print(a)
CodePudding user response:
You can loop through each element, and pull out all LineItems where quantity is not 0.
for element in data:
storage = []
for el in element["LineItems"]:
if float(el['quantity']) != 0:
storage.append(el)
element['LineItems'] = storage
I'm converting the quantity to a float, then comparing it to 0 - that way, you catch quantity == 0, or 0.0, or 0.000000, etc.
CodePudding user response:
wo = [{
"subject": "Test AAA",
"id": "1234",
"LineItems": [
{
"parent_id": "",
"productid": "24x34147",
"sequence-no": "1",
"quantity": "0.000",
"listprice": 0.0
},
{
"parent_id": "",
"productid": "24x34147",
"sequence-no": "2",
"quantity": "5.000",
"listprice": 0.0
}
]
}]
l = len(wo[0]['LineItems'])
for zz in range(l):
z = l - zz -1
if wo[0]['LineItems'][z]['quantity'] == "0.000":
del wo[0]['LineItems'][z]
Iterates through the list backwards and deletes the "0.000" entries. It counts backwards to avoid out of range errors.