删除 Json 文件中的特定行

问题描述 投票:0回答:2

我正在尝试清理下面的 json 文件。我想删除“Stores”列表中键为“Company”的所有字典键值对。

{
"Company": "Apple",
"Stores": [
    {"Company" : "Apple",
     "Location" : "-",
     "Sales": "-",
     "Total_Employees": "-"
     },
    {"Company" : "Apple",
     "Location" : "-",
     "Sales": "-",
     "Total_Employees"
     },
    {"Company" : "Apple",
     "Location" : "-",
     "Sales": "-",
     "Total_Employees": "-"
     },    
]

}

这是我到目前为止的代码:

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))

当我运行它时,我收到 TypeError: 'int' object is not iterable.

python json data-cleaning
2个回答
1
投票

首先,你的 json 是错误的,它缺少

Total_employee
的值。

您可以通过以下方式修改:

{
    "Company": "Apple",
    "Stores": [
        {"Company" : "Apple",
         "Location" : "-",
         "Sales": "-",
         "Total_Employees": ""
        },
        {"Company" : "Apple",
         "Location" : "-",
         "Sales": "-",
         "Total_Employees" : ""
         },
        {"Company" : "Apple",
         "Location" : "-",
         "Sales": "-",
         "Total_Employees": ""
        }    
        ]
}

那么,回答你的第一个问题

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)

0
投票

对问题中显示的数据进行更改(使其有效 JSON)后,您可以执行以下操作:

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()
© www.soinside.com 2019 - 2024. All rights reserved.