Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

336
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda