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
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'", "")
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)
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
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'", "")
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)