I am trying to clean the json file down below. I want to remove all the dict key value pairs for which the key is "Company" in the "Stores" list.
{
"Company": "Apple",
"Stores": [
{"Company" : "Apple",
"Location" : "-",
"Sales": "-",
"Total_Employees": "-"
},
{"Company" : "Apple",
"Location" : "-",
"Sales": "-",
"Total_Employees"
},
{"Company" : "Apple",
"Location" : "-",
"Sales": "-",
"Total_Employees": "-"
},
]
}
This is my code so far:
import json
with open("stores.json", 'r') as jf:
jsonFile = json.load(jf)
print(len(jsonFile))
testJson = {}
for k, v in jsonFile.items():
for key in v:
if not key.startswith('Company'):
print(key)
testJson = jsonFile[key]
print(len(jsonFile))
When I run it im getting TypeError: 'int' object is not iterable.
First off, your json is wrong, it's missing values for Total_employee
.
You can modify it the following way :
{
"Company": "Apple",
"Stores": [
{"Company" : "Apple",
"Location" : "-",
"Sales": "-",
"Total_Employees": ""
},
{"Company" : "Apple",
"Location" : "-",
"Sales": "-",
"Total_Employees" : ""
},
{"Company" : "Apple",
"Location" : "-",
"Sales": "-",
"Total_Employees": ""
}
]
}
Then, to answer your first question
with open('store.json', 'r') as file:
json_data = json.load(file)
if 'Stores' in json_data:
stores = json_data['Stores'] # Gets Stores dictionary
for store in stores:
if 'Company' in store: # Verify if company key exist
del store['Company'] # Delete company key inside Stores
# Convert the modified data back to JSON string
updated_json_string = json.dumps(json_data, indent=4)
with open('updated_data.json', 'w') as file:
file.write(updated_json_string)