简体   繁体   中英

How to read JSON file and transmit to Javascript in HTML organized by Flask?

I am trying to visualize a bunch of data in JSON format by p5js with a server organized by Flask.

Suppose I have a JSON File data.json

[{"a":"1"},{"b":"2"},{"c","3"}]

And my Python code is:

from flask import *

app = Flask(__name__)

def index():
    data_list = json.load(open('data.json'))
    data_json = json.dumps(data_list)
    return render_template("index.html", data_json=data_json)

if __name__ == '__main__':
    app.run(port=7775)

So far I figured out how to send my JSON file to HTML, but how to read the JSON file in HTML through p5js? Here is my HTML code:

<!DOCTYPE html>
<html>

<head>
    <script src="js/p5.js"></script>
    <script src="sketch.js"></script>
</head>

<body>
    Hello
</body>
</html>

At first, actually, it looks that, in Flask, HTML can't read p5.js and sketch.js correctly. The error code is Failed to load resource: the server responded with a status of 404 (NOT FOUND)

Second, I can open the JSON file in HTML by {{data_json}} , but how can I transmit to sketch.js so it can be used for visualization?

What should I do to fix it? Really appreciate your help!

Ideally, your JavaScript would make their own HTTP requests for the data via the Fetch API. This allows you to cache the HTML, while keeping that data separate.

In some cases though, it does make sense to build the data directly into the HTML. For these times, you can use a script tag and serialize the data as JSON again, inside that script tag.

So, in your template:

<script>
  const data = /* your code to serialize and output data here */;
</script>

This sets up the global variable data , which is accessible from your other scripts. Using JSON serialization ensures your data is compatible with JavaScript, without having to worry about any additional escaping. That is, data serialized as JSON can be interpreted by the JavaScript engine, and data will not leak out as arbitrary script.

It's not easy passing python template data to javascript directly so what most people do to achieve the implementation of the functionality of retrieving data is by assigning it to a given html element and querying the element using javascript.

You can checkout this answer A similar question answered

Actually, you don't need any python or libraries. You can use this function:


function readTextFile(file){
    let rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    let txt = '';
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                txt = allText;
            }
        }
    }
  
    rawFile.send(null);
  return txt;
}

and get the content of a file. use JSON.parse() to turn it into an object:

let variable = JSON.parse(readTextFile('info.json'))
document.getElementById('hi').innerHTML = variable;

html: <p id='hi'></p>

your html should have the object displayed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM