0

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!

Haotian Ma
  • 21
  • 1
  • 4

2 Answers2

0

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.

Brad
  • 159,648
  • 54
  • 349
  • 530
  • I got your idea. If I set the global variable `data` in HTML, is it possible that my javascript code encapsulated by `` directly use it? Can I just use it in the `sketch.js` file, or should I do any initialization works? – Haotian Ma Dec 18 '21 at 04:06
  • Yes, if that data is set in a global variable, you'll be able to access it inside sketch.js in this case. – Brad Dec 18 '21 at 04:58
-2

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.

Hermanboxcar
  • 418
  • 1
  • 13
  • 1
    This relies on using `async = false` which is a horrible practice and is deprecated by browser vendors. Please stop suggesting such a practice. Also fetch() supersedes using `XMLHttpRequest` in modern browsers – charlietfl Dec 18 '21 at 04:08
  • You are right. I am trying to use Flask because I want to continuously collect data by constantly running python. But I haven't figured out how to combine Flask and this function now. Thanks for your help! Besides, can you tell me why there is a 404 error? – Haotian Ma Dec 18 '21 at 04:09