1

I have a JSON like this in a list agents_json:

[
  {
    'name': 'ip-10-13-28-114 (5)',
    'active': True
  },
  {
    'name': 'ip-10-13-28-127 (6)',
    'active': True
  },
  {
    'name': 'ip-10-13-28-127',
    'active': True
  }
]

I want to delete the objects from the json where the value of the name matches my variable from a list: agents_to_remove it contains strings like the name value of the third object.

So Problem is my list doesn't contain the number between brackets and a lot of objects have names like that.

Can you tell me if its possible to match the json value with a regex in here:

for i in range(len(agents_json)):
    for j in agents_to_remove:
        regex = re.search(j*)
        if agents_json[i]["name"] == j* :
            agents_json.pop(i)
            break

Obviosly j* isn't working, and after a few hours of searching I still don't have any idea how I could accomplish this.

1

2 Answers 2

1

What you have written looks like JSON - but if this is written in a python file it won't actually be a JSON object, like it might be in javascript, it will be a list of dictionary objects.

It sounds like to want to do some sort of regex or wild card matching to see if an agent in the list appears in the list of agents to be deleted. I don't know exactly what your data looks like but you might try:

remaining_agents = []
for agent in agents_json:
    if any(agent["name"].startswith(x) for x in agents_to_remove):
        continue
    else:
        remaining_agents.append(agent)

agents_json = remainig_agents
Sign up to request clarification or add additional context in comments.

1 Comment

If you would like to find out more about regex's in python take a look at the examples here docs.python.org/3/library/re.html
0

Here is an alternative to MindOfMetalAndWheels solution, using a regular expression

import re

agents_json = [
    {
        'name': 'ip-10-13-28-114 (5)',
        'active': True
    },
    {
        'name': 'ip-10-13-28-127 (6)',
        'active': True
    },
    {
        'name': 'ip-10-13-28-127',
        'active': True
    }
]

agents_to_remove = ['ip-10-13-28-127']

# Iterate through a copy of the list:
for agent in agents_json[:]:
    for regex in agents_to_remove:
        if re.search(regex, agent["name"]):
            agents_json.remove(agent)
            break


print("checking ")

for a in agents_json:
    print(a["name"])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.