在JSON文件中移除特定行

huangapple go评论67阅读模式
英文:

Removing Specific Lines in Json File

问题

I'm here to provide the translated code for you. It seems like you want to remove dictionary key-value pairs where the key is "Company" in the "Stores" list. Here's the code with the translation:

import json

# 打开 JSON 文件并加载数据
with open("stores.json", 'r') as jf:
    jsonFile = json.load(jf)

# 打印 JSON 数据的长度
print(len(jsonFile))
testJson = {}

# 遍历 JSON 数据
for k, v in jsonFile.items():
    # 如果不是 "Company" 键
    if k != "Company":
        for key in v:
            # 如果键不以 "Company" 开头
            if not key.startswith('Company'):
                print(key)
                testJson = jsonFile[key]

# 打印 JSON 数据的长度
print(len(jsonFile))

Please note that this code is a translation of your original code, but it may not achieve the desired result. If you want to remove key-value pairs where the key is "Company" within the "Stores" list, you would need to modify the code accordingly.

英文:

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.

答案1

得分: 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": ""
        }
    ]
}

然后,回答你的第一个问题:

import json

# 从文件中读取 JSON 数据
with open('store.json', 'r') as file:
    json_data = json.load(file)

if 'Stores' in json_data:
    stores = json_data['Stores']  # 获取 Stores 字典
    for store in stores:
        if 'Company' in store:  # 验证是否存在 Company 键
            del store['Company']  # 删除 Stores 内的 Company 键

# 将修改后的数据转换回 JSON 字符串
updated_json_string = json.dumps(json_data, indent=4)

# 将更新后的数据写入文件
with open('updated_data.json', 'w') as file:
    file.write(updated_json_string)

注意:我已经忽略了代码部分,只提供了翻译好的内容。如果你需要进一步的解释或帮助,请随时提出。

英文:

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)

答案2

得分: 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()
英文:

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

huangapple
  • 本文由 发表于 2023年5月26日 16:37:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76339087.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定