Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

332
Vistas
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!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda