What is the best way to transform a list of Python+Flask objects into a list of JavaScript objects?

Here's a Flask application that showcases a list of objects.

from flask import *

app = Flask(__name__)

class Entry: 

    def __init__(self, name, surname):
        self.name = name
        self.surname = surname

entries = [] 

entries.append(Entry('Paul', 'McCartney'))
entries.append(Entry('John', 'Lennon'))
entries.append(Entry('George', 'Harrison'))
entries.append(Entry('Ringo', 'Starr')) 

@app.route('/')
def index():
    return render_template('index.html', entries = entries) 

if __name__ == '__main__':
    app.run(debug=True)

Below is the content of the index.html file:

<html>

<head>
</head>

<body>
    <script>

    var entryName = "{{entries[0].name}}"
    console.log(entryName)

    </script> 
</body>

</html>

When running this code as presented, the console outputs Paul as expected.

However, if you modify the code as follows:

var allEntries = "{{entries}}"
console.log(allEntries[0].name)

The console will display undefined

If you simply output console.log(allEntries), it will show:

[&lt;__main__.Entry object at 0x1065a2278&gt;, &lt;__main__.Entry object at 0x1065a22b0&gt;, 
&lt;__main__.Entry object at 0x1065a22e8&gt;, &lt;__main__.Entry object at 0x1065a2208&gt;] 

To properly handle this list of objects in JavaScript format, some conversion might be required. Any suggestions on how to achieve this? Thank you!

Answer №1

When encountering this error in the past, I found that converting it to a JSON object and then sending it was the most effective solution.

Using Flask:

import json

@app.route('/')
def index():
    jobj = {'data' : entries }
    return render_template('index.html', res=json.dumps(jobj)) 

For JavaScript:

var res = JSON.parse('{{ res | safe }}');
console.log(res.data);

Answer №2

entries consists of Python objects of type Entry. To convert this into a JavaScript object, the best approach is to utilize JSON. JSON serves as an excellent format for data transfer between different systems; however, it necessitates serializing your list first. It's important to note that json.dumps() is effective only with basic data types and not custom classes. As a workaround, we can transform our list of Entry instances into a list of dictionary objects.

main.py:

from flask import *
import json

@app.route('/')
def index():
    return render_template('index.html', entries=json.dumps([ob.__dict__ for ob in entries]))

Subsequently, within your HTML page, employ the safe filter inside the template to notify Jinja2 that the content should be rendered as-is without escaping the HTML or JavaScript code.

index.html:

<script>
    var entries = {{ entries|safe }}
    console.log(entries)
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble loading an image after successfully connecting to an API with react.js

I've been working on a custom fetch component to load images from the "the dog API" onto my page. However, I'm facing some issues with getting the images to display correctly. Can anyone spot what might be missing in my setup? App.js import &apo ...

How to update router query in Next JS without triggering a page change event

I am seeking a solution to modify a URL query for the current page in Next JS without causing the page change event to trigger. Specifically, I need to be able to remember the week that is being viewed in a calendar, much like how Google Calendar operates. ...

What is the best way to utilize a JavaScript variable as a background within an inline style sheet?

I have a fun project for this evening - I am trying to make my website load a different background image every time the page is refreshed. Earlier on in this project, I managed to make the background interact with window size and screen resolution similar ...

Refactor Print Preview Graph Display Issue within Nested Vue Component

I seem to be having trouble accessing this function properly due to an error. I am unsure of how to troubleshoot this issue and determine the correct solution. Any guidance would be greatly appreciated. The component PerformanceDonut.vue is located within ...

Developing a Jquery solution for creating radio buttons layout

Looking to create a radio button functionality within different groups using multiple select. For Group A: If the user selects A1, then it should automatically deselect A2 and A3. If the user selects A2, then it should automatically deselect A1 and A3. I ...

The Express application fails to receive a response from a Mongodb query function

In my current project, I am implementing a simple API Key authentication system. The main goal is to validate the provided key against the user's input. There is a separate file containing a function that queries the database and returns either true/ ...

Transform uploaded image file into a blob format and store it in a VueJS database

I am facing an issue with my form that has multiple inputs, including one of type "file". My goal is to upload an image and then submit the form to the API for storage in the database. <input name="image" class="w-full border-2 border-gray-200 rounded-3 ...

The Gulp task abruptly terminates before the Stream has a chance to trigger the "end" event

const gulpJasmine = require('gulp-jasmine'); const gulpDebug = require('gulp-debug'); function runTest(platform, testType) { const timer = startTimer(); console.log('started!'); return gulp.src('./src/**/_test/**/ ...

Ways to stop Bootstrap 4 dropdown from appearing when clicking on an input field?

Here is a straightforward bootstrap dropdown menu example, but with a twist - the toggle element is a text input. Instead of showing the dropdown on click event, I want it to appear when the user inputs something so I can dynamically populate the menu base ...

Steps to update the value of an object stored within an array

I have a collection of items stored in an array. Each item is represented by an object with properties. I want to update the value of a specific property within each object: var array=[{a:1, b:false}, {a:2, b:true}, {a:3, b:false}] My goal is to set the p ...

Having trouble retrieving the .html() content from the <label> element

Check out the code below: $('.size_click').click(function () { $(this).closest('span').toggleClass('active_size'); $('.selected_sizes').append($(this).closest('label').html()); }); There are multiple ...

How to Conceal the Search Bar in jQuery DataTables

I am having trouble hiding the default search bar in DataTables. Despite trying solutions from this thread, using bFilter:false completely disables filtering, rendering my search boxes in the footer non-functional. I have created a jsfiddle demonstration. ...

Using JQuery to loop through elements when clicked

I've been experimenting with different methods to iterate through a series of 4 li elements, each having a class of "item_n" where n is a number from 1 to 4. I want the iteration to increase by 1 with every click. Despite my efforts, my code isn' ...

Adjusting window size when page is resized

While browsing through SO, I stumbled upon this interesting piece of code: var w = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0], x = w.innerWidth || e.clientWidth || g.clientWidth, y = w. ...

Creating a Singular Instance for Dynamically Loaded Module in Next.js

I'm currently working on creating a Singleton instance for a dynamically imported module in my Next.js app. However, the problem is that each time I call getInstance, it initializes a new instance instead of reusing the existing one. The following co ...

The unsightly square surrounding my sprite in Three.js

I am attempting to create a beautiful "starry sky" effect using Three.js. However, I am encountering an issue where my transparent .png star sprites have a colored outline around them. Here is the sprite I am using: https://i.sstatic.net/2uylp.png This ...

Issues with fetching data from a Drupal module using an Ajax call

I have created a custom module in Drupal where the .js file is supposed to make an ajax call to a .module file. However, I am facing issues as the ajax call is not functioning properly. Can someone please assist me with this? Below is my .js file: // Jqu ...

Retrieve and dynamically load an entire webpage using AJAX

Although it's typically not recommended, I am interested in displaying the progress of a download on a heavy page to show the user when it's ready. Is there a way for me to track and display the actual progress of the download? Can I monitor how ...

Can we trust the accuracy of Function.prototype.toString for our needs?

Can I trust Function.prototype.toString to provide a valid javascript function string for user-defined functions? Do any popular javascript engines differ in how they represent function objects as strings? I came across this question, but it doesn't ...

Accept JSON data in ASP.NET MVC action method for posting data

I have a model class named Parcel which contains the parameters Name and CenterPoint: public class Parcel { public string Name { get; set; } public object CenterPoint { get; set; } } The values for these parameters are obtained from a map. When a ...