Home > Software engineering >  Remove key value in a JSON file
Remove key value in a JSON file

Time:04-30

I have created a function to convert the data of csv file to a JSON. Now, the file is being created in the correct format but I want to delete key from the JSON files. For example the market code.

def csvConvert(csv_path, json_path):
    
    jsonData={}
    
    with open(csv_path, encoding='utf-8') as csvfile:
        
        csvData = csv.DictReader(csvfile)
        
        for rows in csvData:
            key = rows['CC']
            jsonData[key] = rows
            
    with open(json_path, 'w', encoding='utf-8') as jsonfile:
          jsonfile.write(json.dumps(jsonData, indent=5))

CodePudding user response:

I believe you are looking or the del operator: https://docs.python.org/3/reference/simple_stmts.html#del.

del can be used to remove entries in dictionaries (which is what csvData is):

>>> x = {'a': 1, 'b': 2}
>>> x
{'a': 1, 'b': 2}
>>> del x['a']
>>> x
{'b': 2}

CodePudding user response:

You can just delete it before adding it to dictionary being created.

def csvConvert(csv_path, json_path):

    jsonData={}

    with open(csv_path, encoding='utf-8', newline='') as csvfile:
        csvData = csv.DictReader(csvfile)
        for row in csvData:
            key = row['CC']
            del row['CC']  # <--- Delete key before adding to jsonData.
            jsonData[key] = row

    with open(json_path, 'w', encoding='utf-8') as jsonfile:
          jsonfile.write(json.dumps(jsonData, indent=5))

  • Related