pythondictionaryflask

is there a way to only select the value from a dictionary from a json file?


i have a website which im hosting with flask and using mongodb to store data. i am using htmx to reset the data, but i am running into a problem; when the data resets, it shows the entire dictionary, when i only want the value from the dictionary. it seems like it would be an easy fix, but because i am so new to htmx i have no idea what to do.

heres my current flask setup:

@app.route('/data')
def get_data():
    return json.loads(dumps(collection.find()))

and my html:

<h1>MongoDB Data Test</h1>
<div id="data-container" 
   hx-get="/data" 
   hx-trigger="load, every 3s" 
   hx-target="#data-container" 
   hx-swap="innerHTML">
   <!-- Data will be injected here -->
   <span></span>
</div>

this is what is shown on the website: [ { "_id": { "$oid": "id" }, "count_testing": 15 } ] i only want the count_testing value (i.e. 15), not the entire dictionary to be shown on the website.


Solution

  • The best way to do it would be on the Python side IMO. Put data in a variable, run a list comprehension on it, return the output. Like:

    def get_data():
        data = list(collection.find()) 
        filtered_data = [item['count_testing'] for item in data if 'count_testing' in item]
        return jsonify(filtered_data)