remove k,v from http response in python

Viewed 38

I am new to python and am struggling with remove a key and value from a json return by an http request. When querying a task I get the following back.

data = requests.get(url,headers=hed).json()['data']
[{
    'gid': '12011553977',
    'due_on': None,
    'name': 'do something',
    'notes': 'blalbla,
    'projects': [{
        'gid': '120067502445',
        'name': 'Project1'
    }]
}, {
    'gid': '12002408815',
    'due_on': '2021-10-21',
    'name': 'Proposal',
    'notes': 'bla',
    'projects': [{
        'gid': '12314323523',
        'name': 'Project1'
    }, {
        'gid': '12314323523',
        'name': 'Project2'
    }, {
        'gid': '12314323523',
        'name': 'Project3'
    }]

I am trying to remove 'gid' from all projects so projects look like this

    'projects': [{
        'name': 'Company'
    }]

What is the best way to do this with python3?

1 Answers

You can use recursion to make a simpler function to handle all elements and sub-elements. I haven't done extensive testing, or included any error checking or exception handling; but this should be close to what you want:

def rec_pop(top_level_list,key_to_pop='gid'): 
    for item in top_level_list: 
        item.pop(key_to_pop) 
        for v in item.values(): 
            if isinstance(v,list): 
                rec_pop(v)

# call recursive fn
rec_pop(data)

Result:

In [25]: data
Out[25]: 
[{'due_on': None,
  'name': 'do something',
  'notes': 'blalbla',
  'projects': [{'name': 'Project1'}]},
 {'due_on': '2021-10-21',
  'name': 'Proposal',
  'notes': 'bla',
  'projects': [{'name': 'project2'}]}]
Related