Reputation: 45
I have a set of JSON in MongoDB collections which are received by webhooks and I don't have control of that and elements of one set wont be same for another. I'm able to retrieve those elements which has same key for all other data. But I need to retrieve those data irrespective of whether its present in other documents or not. Attaching the pic of values present in MongoDB.
I'm using below code to insert webhooks to MongoDB
@app.route('/webhook', methods=['POST', 'GET'])
def respond():
collection10 = db['webhooks']
a = request.get_json()
print(a)
collection10.insert_many(a)
return render_template("signin.html")
Suppose I try to retrieve "_id", I can easily retrieve since both the data has "_id". But if I try to retrieve those elements which are present in one and not in another I get an error.
I'm using this code to retrieve elements:
@app.route('/webhookdisplay', methods=['POST', 'GET'])
def webhooksdis():
collection10 = db['webhooks']
for i in collection10.find({}):
posts = i['name']
print(posts)
return render_template("webhooks.html", posts = posts)
For the above code I get error
KeyError: 'name'
If I retrieve "_id" in the same fashion as mentioned above it'll be retrieved.
Expected outcome: I need to retrieve nested data irrespective whether its present in other data or not. It would be great if there are any other approaches to display particular data in the form of table in HTML page
Purpose Once I get individual data, I can render the same in frontend using Jinja in the form of table
Upvotes: 0
Views: 294
Reputation: 8814
If you're not sure whether the returned record will contain a particular key, then you should use the built-in .get()
function. which returns None by default if the key isn't present, unlike using the square bracket references. This will avoid the KeyError exception your are seeing.
posts = i.get('name')
if posts is None:
# Handle logic if name doesn't exist
EDIT: If you need a nested field:
name = i.get('data', {}).get('geofence_metadata', {}).get('name')
Upvotes: 1