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

248
Vistas
How do I get a JS script to parse raw JSON from a file?

I have a really simple JSON data file with no kind of wrapping, e.g.:

[{"name:","fakename"}, {"lang:", "javascript"}]

I'm trying to use this data in a js script in the same directory. I'm reading in both files in the document <head>, like such:

<script id="myJSON" src="data.json"></script> 
<script src="myScript.js"></script> 

and then the part I'm stuck on is how to get myScript to SEE that JSON data. In the script I can do:

d =  document.getElementById("myJSON"); 
console.log(d); 

The script returns the DOM element "myJSON" but I don't know how to access its JSON contents. I figured it would be a property like 'text' or 'value' or 'innerHTML' but I don't see it anywhere. I've tried various combinations of the type attribute in the tag but none of that makes any difference.

I know I could use an API like fetch but that's more complexity than I want. My best idea so far is to edit the json file to put an identifier at the beginning of the json file, like var myJSON = '[{"json"}]'; so then myScript would have a clear handle to JSON.parse(myJSON). But that's an extra step in an automated process which I don't want (or think I need).

How do I get my JS to see this "anonymous" JSON?

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

0

If you don't want to use fetch, you could use the server side code (PHP, ASP, etc) to write the text of the JSON into a hidden div in the page, and then you could use getElementByID to get the text, followed by parse to get an object that represents the JSON data.

about 4 years ago · Juan Pablo Isaza Denunciar

0

This was not that much extra code but it was kind of a pain to wrap my head around. I had to wrap everything in a .then clause of fetch, or of an async function which called fetch. Here's what my code ended up looking like.

 readJSONFile().then(jq => {
          for (i = 0; i < jq.length; ++i) {
                console.log( jq[i].myJSONKey )
          });
async function readJSONFile() {
    const response = await fetch('data.json');
    const jq = await response.json();
    return jq;
}
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