Transfer data as JSON from Flask to JavaScript

Having trouble sending data from Flask to JavaScript. I have the information from the database and added it to a dictionary. Now, I want to convert this data into a JSON object in JavaScript to display it on a map. Despite using JSON.parse in JavaScript, it's not working as expected.

Code in route.py

@app.route('/mapaa',methods=['GET','POST'])
def mapa():
    slownik = {}
    if 'event_form' in request.form:
        name = request.form['name_event']
        all_data = Event.query.filter_by(name=name).all()
        for row in all_data:
            slownik.update({'id':row.id})
            slownik.update({'date_st':row.date_start})
            slownik.update({'date_end':row.date_end})
            slownik.update({'type':row.type})
            slownik.update({'name':row.name})
            slownik.update({'len_route':row.len_route})
            slownik.update({'route':row.route})
    return render_template('mapaa.html', title='Mapa',data=slownik)

In JavaScript mapa.js:

 var parsed = JSON.parse('{{data | tojson}}');
 console.log(data)

However, it returns:

VM475:1 Uncaught SyntaxError: Unexpected token { in JSON at position 1
    at JSON.parse (<anonymous>)

What could be wrong? Note that date_end and date_start are datetime types. I also tried to use jsonify with this dictionary but it didn't work either.

Answer №1

To incorporate the JSON data into your template, you can utilize the mappa.html scriptelement by utilizing thejson and [tojson`]() filter:

<script>
    var parsedData = {{ jsonData | tojson | safe}};

    console.log(parsedData)
</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

Utilizing dynamic JSON lists in Spring MVC

Currently, I have a new form for Person that includes a table of objects structured like so: <table class="table table-striped table-condensed flip-content"> <thead class="flip-content"> <tr> <th width="20%"> ...

Tips for automatically closing a Bootstrap 3 modal when AJAX request succeeds?

I'm trying to close a modal upon ajax success, but I'm encountering an issue. Here is my code snippet: Javascript success: function() { console.log("delete success"); $('#deleteContactModal').modal('hide'); $( "# ...

Preloading Vue dynamic routes for optimal performance

Currently dealing with a challenge on my Vue project and could use some help. I'm looking to prerender specific dynamic routes when I navigate to a particular route within the application. On the /works route, there's a list of items displa ...

Enquire.js does not compute accurately at first glance, but only after adjustments are made during

Currently, I am working on incorporating media queries using Enquire.js and Vue.js. The functionality seems to be in good shape when manually resizing the browser window. However, upon loading the document, no match is detected. This peculiar behavior beco ...

The functionality of $watch in AngularJS is not meeting the desired outcomes

Within my controller, I am looking to receive notifications when the value of a certain variable changes. Specifically, I want a function to be triggered whenever this variable is updated. To achieve this, I am utilizing the $watch method in AngularJS. Her ...

What is the process for transforming the values brought in by ImportJSON into numeric values?

After some investigation, I've come to realize that values brought into Google Spreadsheets using ImportJSON are actually considered as text rather than numeric. As a result, they cannot be easily summed up. Is there a way to convert these values int ...

Is it possible to apply JavaScript object destructuring but make changes to certain values before assigning them to a new object?

After receiving movie data from an api, I am currently manually creating a new object with a subset of properties and modified values. Is there a more efficient way to achieve this using javascript/typescript object destructuring syntax? I specifically wa ...

Comparing the differences between while loops and setTimeout function in JavaScript

I'm currently deciding between using a while loop or a setTimeout function in JavaScript. As I understand it, due to JavaScript's single-threaded nature, having one function run for an extended period can hinder the execution of other functions s ...

Display a separate component within a primary component upon clicking a button

Looking to display data from a placeholder module upon component click. As a beginner with React, my attempts have been unsuccessful so far. I have a component that lists some information for each element in the module as a list, and I would like to be ab ...

Dealing with lag problems while feeding a massive dataset into the Autocomplete component of Material-UI

In my React project, I have integrated the Autocomplete component from Material-UI to enhance user experience. However, when attempting to pass a large dataset of 10,000 items to the Autocomplete component as a prop, there is a noticeable delay of approxim ...

How to easily update a URL string in Angular 5 router without altering the state of the application

I am working on an Angular 5 application that utilizes the angular router. The majority of my entry route components are placed under a context id, which represents a name in the app store along with other relevant data for that context. Even though the na ...

What is the best approach to breaking down attributes upon import according to the theme?

Hey there! Here's the thing - I have this file called <code>colors.ts:

export const black = '#0C0C0C'; export const blue = '#22618E'; Whenever I need to use a color, I import it like so: import {black} from 'Shared& ...

What are the best practices for utilizing ESM only npm packages alongside traditional npm packages within a single JavaScript file?

Hey there, I'm fairly new to web development and I encountered a problem when trying to require two packages, franc and langs, in my index.js file. It turns out that franc is now an ESM only package, requiring me to import it and mention type:module i ...

Prepare information for Flot Pie to work with

Despite sharing data that Flot can accept, the graph is not being displayed on my client. Furthermore, an error occurs when trying to parse the JSON string. See code snippet below: //server_processing.aspx.cs [WebMethod] public static string G ...

Dependencies in AngularJS factories

I'm currently using AngularJS to extract data from mongodb. I have been attempting to utilize a factory to retrieve this information through the $http method. Despite researching and trying numerous approaches, none seem to work for me. In addition t ...

Getting row data in datatables after a button click: A step-by-step guide

Could somebody provide assistance with retrieving a single row of data on a click event? This table is dynamically populated after the AJAX call's Success function is executed <div class="table-responsive table-wrap tableFixHead container-flu ...

Switch the visibility of a div tag using Next.js

Script export default function Navigation(){ let displayMenu = false; function toggleMenu() { displayMenu = !displayMenu; } return ( <> <button onClick={toggleMenu}>Toggle Navigation</button> {/*This code sh ...

Access an attribute using slashes in Jquery

I've been struggling to use jQuery to select an object based on a unique filename attribute. However, I'm facing issues with escaping slashes when the selector is created using a variable. Despite spending hours trying different combinations, I s ...

Warning in Next.js: Each element in a list requires a distinct "key" property

Currently, I am in the process of building an e-commerce platform using Nextjs. My current focus is on enhancing the functionality of the myCart page, which serves as a dashboard for displaying the list of items that have been ordered. Below is the code s ...

Is a Selenium loop a viable option?

</head> <body> <table cellpadding="1" cellspacing="1" border="1"> <thead> <tr><td rowspan="1" colspan="3">test</td></tr> </thead><tbody> <tr> <td>click& ...