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

SignalR's postback interrupts the functionality of jQuery actions

On my screen, I have a widget that updates data and changes its class based on server-side interactions. It also responds to mouse clicks. To notify multiple clients of updates simultaneously, I'm using SignalR. The problem arises when I wrap everythi ...

The object NativeModules from the 'react-native' requirement is currently empty

At the top of one of the node_modules utilized in my project, there is a line that reads: let RNRandomBytes = require('react-native').NativeModules.RNRandomBytes However, I've noticed that require('react-native').NativeModules ...

What Occurs to Processed Messages in Azure Functions if Result is Not Output?

I have created an Azure function that is connected to the messaging endpoint of an IoT Hub in order to trigger the function for all incoming messages. The main purpose of this function is to decompress previously compressed messages using GZIP before they ...

Tips for modifying JSON property names during the parsing process

As outlined in the JSON.parse documentation, a reviver function can be utilized to modify the value of each property within the JSON data. Here is an example: JSON.parse('{"FirstNum": 1, "SecondNum": 2, "ThirdNum": 3}', function(k, v) { return ...

What is the best method for regularly importing large JSON datasets into Cloud Firestore?

I have a task to import a large JSON file containing 180k records. Currently, I am able to upload only 500 records per run using the code below, but I need to find a way to efficiently upload all 180k records periodically. My Objectives: Successfully par ...

Receiving a 405 Method Not Allowed error when accessing a WCF REST service using jQuery

I've developed a WCF rest service that needs to be accessed through jQuery. The service is currently running on my local machine. However, it seems to only accept GET requests, as any other method results in a 405 (Method Not Allowed) error. I'm ...

Removing a row from MySQL using JQuery Ajax

Hello there! I'm currently facing an issue while trying to remove a row from a MySQL database using PHP and AJAX. I initially thought it would be a simple task with $.ajax {}, but unfortunately, the row is not getting deleted for some reason. Here&apo ...

What are the risks of employing conditional rendering in react-router-dom for authentication purposes?

In the following code snippet: If the authentication data sent from the client matches in the backend, a response with the user ID is sent. If setIsAuth sets to true, the Layout Component will display the first case within the Switch component, allowin ...

Can we ensure that the function is called when a node is located?

Presently, I am executing the following code but it is causing the call stack to slow down; how can I optimize this using either an async await or more advanced promise functions? I have a dynamic node that is added to the DOM at different times dependin ...

The issue with jquery slideToggle is that it mistakenly opens all divs instead of just the specific div that should

My website has a dynamic page with a variable number of <div> elements. The concept is that users can click on the + symbol, which is represented by an <img> tag, to display the corresponding div. Currently, my code includes: PHP/HTML $plus ...

Using the Map Function in React JS to Dynamically Render Radio Buttons with Material-UI

Hey everyone, I'm looking for some assistance in replacing the old classic radio button with a new one using material-ui. I've been trying but haven't been successful so far. Any suggestions would be greatly appreciated. Thanks in advance. Y ...

The jQuery .post function is successfully executing, but it is strangely triggering the .fail method without

My data is successfully being posted, but I'm struggling to get my .post response handler code to work efficiently. The results seem inconsistent across different browsers and tools that I have tried. Here's the code snippet for the post: $.post ...

creating a personalized JSON response format in Go

Using the "encoding/json" package, I am able to output in JSON format. However, I want to customize the response structure. Below is a snippet of the code: var people []Person people = append(people, Person{Id: "1", Firstname: "John", Lastname: "Doe", Add ...

React-virtualized list experiencing performance problems due to react-tether integration within its elements

Description I need help with a challenging issue. I have a long list of items displayed in a react-virtualized VirtualScroll. Each item on the list contains many elements, including one that triggers a context menu. I'm using react-tether to attach t ...

What is the procedure for utilizing the comparator to arrange items according to various attributes?

I am trying to find a way to arrange my models in a collection based on their required flag and then alphabetically by their value. This is what my current code looks like: var myModel = Backbone.Model.extend({ defaults: { required: true, ...

Display data from a PHP array in a JavaScript alert box

Within my Wordpress registration form, I am attempting to display the $error array in an alert message. I have experimented with using console.log(), but it does not show any output. Even when using JSON.stringify(), the alert only displays the word: true ...

A Guide to Effortlessly Implementing moment.js into a React TypeScript Application

I'm attempting to implement code splitting and one of the specific packages I want to separate into its own chunk is moment.js. Here's how I'm doing it: const myFunc = async (currentNumber) => { const moment = (await import('momen ...

Advantages and Disadvantages of Implementing Ajax for Form Validation

Exploring the benefits of validating forms with Ajax, I find it to be a valuable tool in preventing code redundancy. However, before making the switch, I am curious about any potential drawbacks compared to traditional JavaScript validation. While I have c ...

Tips for transferring a set-returning function to a LATERAL JOIN in PostgreSQL

Attempted Query: select created_at, sum((json_array_elements(shipping_lines::json) ->> 'price')::float) as shipping_price from t1 group by 1 Error Encountered: ERROR: aggregate function calls cannot contain set-returning function calls ...

Encountering an issue with undefined ID when utilizing a radio input field in Vue JS

I'm facing an issue and I hope you can assist me with it. My webpage contains Vue scripts and a list of radio selections rendered via Liquid tag and GraphQL results. The problem arises when I click the submit button or select a radio option, resultin ...