2

I have a JSON response and I need to remove a property including the value and add it to a new list parsed in a JSON object as a response.

The JSON response is:

 [
    {
        "bookmark": "bla",
        "entity_name": "aag",
        "id": 56
    },
    {
        "bookmark": "ag",
        "entity_name": "dsg",
        "id": 34
    },
    {
        "bookmark": "agds",
        "entity_name": "dsaga",
        "id": 12
    }
   ...
]

I want to ammend this but splicing some of its properties (e.g. 'bookmark') and send it back as a JSON object.

It goes like this.

[
    {
        "entity_name": "aag",
        "id": 56
    },
    {

        "entity_name": "dsg",
        "id": 34
    },
    {

        "entity_name": "dsaga",
        "id": 12
    }
    ...
]

I have tried many ways but can't seem to get my desired output as above.

if the new list is similar to above:

return jsonify(newList)

Any suggestions would be highly helpful. Thank you

3
  • 1
    Can you show us your code? Commented Apr 26, 2019 at 3:39
  • So basically you just need to take the bookmark key out? Commented Apr 26, 2019 at 3:47
  • @gmds -yes exactly that Commented Apr 26, 2019 at 3:48

4 Answers 4

7

For python

You can use del operator

Using your example

_collections = [{
    'bookmark': 'bookmark',
    'entity_name': "aag",
    'id': 56
},
{
    'bookmark': 'bookmark',
    'entity_name': "aag",
    'id': 56
},
{
    'bookmark': 'bookmark',
    'entity_name': "aag",
    'id': 56
}
]

for item in _collections:
    del item["bookmark"]

print(_collections)

For javascript

You can use delete operator.

Using your example:

var _firstCollection =  [
    {
        "bookmark": "bla",
        "entity_name": "aag",
        "id": 56
    },
    {
        "bookmark": "ag",
        "entity_name": "dsg",
        "id": 34
    },
    {
        "bookmark": "agds",
        "entity_name": "dsaga",
        "id": 12
    }
];

_firstCollection.forEach(item => {
   delete item.bookmark; // removes bookmark property of every item
});
console.log(_firstCollection);
Sign up to request clarification or add additional context in comments.

1 Comment

This is a Python question
4

Use the json library:

data = ...  # put your JSON object here

result = json.dumps([{k: v for k, v in d.items() if k != 'bookmark'} 
                     for d in json.loads(data)])
print(result)

Output:

[
  {"entity_name": "aag", "id": 56}, 
  {"entity_name": "dsg", "id": 34}, 
  {"entity_name": "dsaga", "id": 12}
]

There are a few steps to this solution.

First, if your input is a JSON object, then it must be converted to the appropriate Python object (usually a nested dict or list). That is done with json.loads (I remember it as "JSON load string").

Next, we can use a simple comprehension to get the result we want, which is a list of the same size, just with the 'bookmark' key from each dict in it removed. The comprehension used is equivalent to the following:

loaded = json.loads(data)

result = []

for d in result:
    new_d = {}
    for key, value in d.items():
        if key != 'bookmark':
            new_d[key] = value

    result.append(new_d)

Lastly, of course, we convert our result back into a JSON object with json.dumps.

3 Comments

Wow! Thanks a lot, could you kindly explain me what you did
@gmds used [docs.python.org/3/tutorial/… comprehensions here, iterating each of entity and filtering keys with the if condition
This is perfect for filtering out 'ResponseMetadata' from boto3 responses.
0

You can use pop while iterating over your data.

import json
entities = [
    {
        "bookmark": "bla",
        "entity_name": "aag",
        "id": 56
    },
    {
        "bookmark": "ag",
        "entity_name": "dsg",
        "id": 34
    },
    {
        "bookmark": "agds",
        "entity_name": "dsaga",
        "id": 12
    }
]

for entity in entities:
  entity.pop("bookmark")

print(json.dumps(entities))

N.B. If you want to filter out multiple keys then you can do:

for entity in entities:
    for key in ["bookmark", "foo", "bar"]:
        entity.pop(key)

Comments

0
#You can do this without using json library as well-

mySourceList=[{"bookmark": "bla","entity_name": "aag","id": 56},{"bookmark": "ag","entity_name": "dsg","id": 34},{"bookmark": "agds","entity_name": "dsaga","id": 12}]

myTargetList=[]

for dict in mySourceList:
    myTempList=[]
    myTempDict={}
    for key,value in dict.items():
        if(key in ["entity_name","id"]):
            myTempList.append((key,value))
    myTempDict.update(myTempList)
    myTargetList.append(myTempDict)

print(myTargetList)

#O/P- [{'entity_name': 'aag', 'id': 56}, {'entity_name': 'dsg', 'id': 34}, {'entity_name': 'dsaga', 'id': 12}]

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.