Removing Specific Lines in Json File

Question:

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.

Asked By: kingmic

||

Answers:

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 dictionnary
    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)
Answered By: Sparkling Marcel

Having made changes to the data shown in the question (to make it valid JSON) you could do this:

import json
import os

FILENAME = '/Volumes/G-Drive/foo.json'

with open(FILENAME, 'r+') as data:
    d = json.load(data)
    for store in d.get('Stores', []):
        try:
            del store['Company']
        except KeyError:
            pass
    data.seek(0, os.SEEK_SET)
    json.dump(d, data, indent=2)
    data.truncate()
Answered By: DarkKnight
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.