skip to Main Content

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


  1. 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'", "")
    
    Login or Signup to reply.
  2. 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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search