How can I delete a item in a list from a JSON file in Python?

Question:

Hello I’m using a JSON file for some project and I need help to delete a str from a JSON string list.

Here is my JSON file content:

{"language": "['English', 'French', 'Spanish']", "bank": 50}

I would like to remove ‘Spanish’ from the JSON file list.

How can I do it?


import json

with open("example.json", "r") as jsonFile:
    data = json.load(jsonFile)

del list(data["language"]['Spanish'])

with open("example.json", "w") as jsonFile:
    json.dump(data, jsonFile)

This gives me some error:

cannot delete function call

Asked By: BatteTarte

||

Answers:

You are trying to make a list from data["language"]["Spanish"] which cause an error.

As I can see in your sample data, you have a string which you want to delete something from. You can do it by replace:

data = json.load(jsonFile)
data["language"] = data["language"].replace(", 'Spanish'", "")
Answered By: Amin

You can try something like this:

import json


data = {'language': '["English", "French", "Spanish"]', 'bank': 50}
language_array = json.loads(data["language"])
language_array.remove('Spanish')
data['language'] = json.dumps(language_array)
Answered By: kamran890
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.