I’m working on a project that uses a JSON file, and I’m having trouble removing a string from a list within the JSON file. Here’s an example of what my JSON file looks like:
{"language": "['English', 'French', 'Spanish']", "bank": 50}
I would like to remove the string ‘Spanish’ from the ‘language’ list in the JSON file. Can anyone help me with this?
Here’s what I’ve tried so far, but I’m getting an error message:
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)
The error message is "cannot delete function call". If anyone could offer some guidance on how to fix this, I would greatly appreciate it. Thank you in advance for your help!
2
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
:You can try something like this: