Data exchange between Flask and Javascript


I wrote a simple application in Python Flask. There is a page, part of which should be updated after a certain interval (for example, 1 second). I have no idea how to implement this on Flask, so I decided to use JavaScript (I’m practically not familiar with this language). The script accesses the Flask server at a specific URL every second and receives data in JSON format. In Python, the handler for this URL sends a response using the jsonify() function. The object being sent is an array of dictionaries in Python – [{key: value,...}, {key: value,...},...]. In JavaScript, I get (probably) an array of objects – [object Object], [object Object]. My question is how do I get a similar object in JS, as in Python, in order to correctly extract the information.
In Python:

[{'sender': '', 'recipient': [''], 'amount': 1, 'message': 'hi'}, 
{'sender': '', 'recipient': [''], 'amount': 1, 'message': 'hello'}]

In JS:

[object Object], [object Object]

URL handler, messages – an array of dictionaries:

@app.route('/consensus', methods=['GET'])
def consensus():
    messages = blockchain.resolve_conflicts()
    return jsonify(messages=messages)

JS script, the html page has a block with the ID #message

    setInterval(function () {
                $SCRIPT_ROOT = {{ request.script_root|tojson|safe }}
                    function(data) {
    , 10000)


Try this to see what the objects are composed of:


Then you need to learn about accessing object properties. What is happening is your object is being converted to a string, which for any JS object it’s string value is object Object by default.

If your object is like this: x = {name: 'Tom'} then if you print the object (x) it prints object Object – but if you print it will print tom.

In other words, you need to format your string and not just print the object’s string value.

There are lots of examples of how to do this, here are a few:

Answered By – mikeb

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published