Cargando archivo JSON local


Estoy intentando cargar un archivo JSON local pero no funcionará. Aquí está mi código JavaScript (usando jQuery:

var json = $.getJSON("test.json");
var data = eval("(" +json.responseText + ")");
document.write(data["a"]);

La prueba.archivo json:

{"a" : "b", "c" : "d"}

No se muestra nada y Firebug me dice que los datos no están definidos. En Firebug puedo ver json.responseText y es bueno y válido, pero es extraño cuando copio la línea:

 var data = eval("(" +json.responseText + ")");

En la consola de Firebug, funciona y puedo acceder a los datos.

Alguien tiene una solución?

Author: Danny Beckett, 2011-09-08

21 answers

$.getJSON es asíncrona por lo que debe hacer:

$.getJSON("test.json", function(json) {
    console.log(json); // this will show the info it in firebug console
});
 235
Author: seppo0010,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-22 20:19:28

Tenía la misma necesidad (para probar mi aplicación angularjs), y la única manera que encontré es usar require.js:

var json = require('./data.json'); //(with path)

Nota: el archivo se carga una vez, otras llamadas usarán la caché.

Más sobre la lectura de archivos con nodejs: http://docs.nodejitsu.com/articles/file-system/how-to-read-files-in-nodejs

Requerir.js: http://requirejs.org /

 124
Author: Ehvince,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-11 14:48:13

Si desea que el usuario seleccione el archivo json local (en cualquier lugar del sistema de archivos), entonces la siguiente solución funciona.

Utiliza FileReader y JSON.parser (y sin jquery).

<html>
<body>

<form id="jsonFile" name="jsonFile" enctype="multipart/form-data" method="post">

  <fieldset>
    <h2>Json File</h2>
     <input type='file' id='fileinput'>
     <input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
  </fieldset>
</form>


<script type="text/javascript">

  function loadFile() {
    var input, file, fr;

    if (typeof window.FileReader !== 'function') {
      alert("The file API isn't supported on this browser yet.");
      return;
    }

    input = document.getElementById('fileinput');
    if (!input) {
      alert("Um, couldn't find the fileinput element.");
    }
    else if (!input.files) {
      alert("This browser doesn't seem to support the `files` property of file inputs.");
    }
    else if (!input.files[0]) {
      alert("Please select a file before clicking 'Load'");
    }
    else {
      file = input.files[0];
      fr = new FileReader();
      fr.onload = receivedText;
      fr.readAsText(file);
    }

    function receivedText(e) {
      let lines = e.target.result;
      var newArr = JSON.parse(lines); 
    }
  }
</script>

</body>
</html>

Aquí hay una buena introducción en FileReader: http://www.html5rocks.com/en/tutorials/file/dndfiles /

 61
Author: Trausti Kristjansson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-02 08:39:56

Si está buscando algo rápido y sucio, simplemente cargue los datos en la cabeza de su documento HTML.

Datos.js

var DATA = {"a" : "b", "c" : "d"};

Índice.html

<html>
<head>
   <script src="data.js" ></script>
   <script src="main.js" ></script>
</head>
...
</html>

Main.js

(function(){
   console.log(DATA) // {"a" : "b", "c" : "d"}
})()
 49
Author: jwerre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-10 21:19:51

De una manera más moderna, ahora puede usar la API Fetch :

fetch("test.json")
  .then(response => response.json())
  .then(json => console.log(json));

Todos los navegadores modernos soportan Fetch API. (Internet Explorer no, pero Edge sí!)

Fuente:

 42
Author: aloisdg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-16 11:05:49

As.webgeeker.xyz

function loadJSON(callback) {
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', 'my_data.json', true);
    // Replace 'my_data' with the path to your file
    xobj.onreadystatechange = function() {
        if (xobj.readyState === 4 && xobj.status === "200") {
            // Required use of an anonymous callback 
            // as .open() will NOT return a value but simply returns undefined in asynchronous mode
            callback(xobj.responseText);
        }
    };
    xobj.send(null);
}

function init() {
    loadJSON(function(response) {
        // Parse JSON string into object
        var actual_JSON = JSON.parse(response);
    });
}

Versión ES6

const loadJSON = (callback) => {
    let xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', 'my_data.json', true);
    // Replace 'my_data' with the path to your file
    xobj.onreadystatechange = () => {
        if (xobj.readyState === 4 && xobj.status === "200") {
            // Required use of an anonymous callback 
            // as .open() will NOT return a value but simply returns undefined in asynchronous mode
            callback(xobj.responseText);
        }
    };
    xobj.send(null);
}

const init = () => {
    loadJSON((response) => {
        // Parse JSON string into object
        let actual_JSON = JSON.parse(response);
    });
}
 13
Author: xgqfrms,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-04 05:59:28

Try es tal manera (pero también tenga en cuenta que JavaScript no tiene acceso al sistema de archivos del cliente):

$.getJSON('test.json', function(data) {
  console.log(data);
});
 6
Author: Samich,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-08 10:31:41

Recientemente D3js es capaz de manejar archivos json locales.

Este es el problema https://github.com/mbostock/d3/issues/673

Este es el parche para que D3 funcione con archivos json locales. https://github.com/mbostock/d3/pull/632

 6
Author: ns-1m,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-23 07:44:55

No puedo creer cuántas veces se ha respondido a esta pregunta sin entender y/o abordar el problema con el código real del Póster Original. Dicho esto, yo mismo soy un principiante (solo 2 meses de codificación). Mi código funciona perfectamente, pero no dude en sugerir cualquier cambio en él. Aquí está la solución:

//include the   'async':false   parameter or the object data won't get captured when loading
var json = $.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false});  

//The next line of code will filter out all the unwanted data from the object.
json = JSON.parse(json.responseText); 

//You can now access the json variable's object data like this json.a and json.c
document.write(json.a);
console.log(json);

Aquí hay una forma más corta de escribir el mismo código que proporcioné anteriormente:

var json = JSON.parse($.getJSON({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText);

También puedes usar $.ajax en lugar de $.getJSON para escribir el código exactamente de la misma manera:

var json = JSON.parse($.ajax({'url': "http://spoonertuner.com/projects/test/test.json", 'async': false}).responseText); 

Finalmente, la última forma de hacer esto es envolver $.ajax en una función. No puedo tomar el crédito por este, pero lo modifiqué un poco. Lo probé y funciona y produce los mismos resultados que mi código anterior. Encontré esta solución aquí > > cargar json en variable

var json = function () {
    var jsonTemp = null;
    $.ajax({
        'async': false,
        'url': "http://spoonertuner.com/projects/test/test.json",
        'success': function (data) {
            jsonTemp = data;
        }
    });
    return jsonTemp;
}(); 

document.write(json.a);
console.log(json);

La prueba .el archivo json que ves en mi código anterior está alojado en mi servidor y contiene el mismo objeto de datos json que él (el póster original) había publicado.

{
    "a" : "b",
    "c" : "d"
}
 6
Author: SpoonHonda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:47

Me sorprende que la importación desde es6 no se haya mencionado (usar con archivos pequeños)

Ex: import test from './test.json'

Webpack 2json-loader como predeterminado para los archivos .json.

Https://webpack.js.org/guides/migrating/#json-loader-is-not-required-anymore

For TypeScript :

import test from 'json-loader!./test.json';

TS2307 (TS) No puede encontrar el módulo 'json-loader!./suburbio.json '

Para que funcione tuve que declarar el módulo primero. Espero que esto salve a algunos horas para alguien.

declare module "json-loader!*" {
  let json: any;
  export default json;
}

...

import test from 'json-loader!./test.json';

Si intenté omitir loader de {[3] } obtuve el siguiente error de webpack:

BREAKING CHANGE: Ya no se permite omitir el sufijo '- loader' cuando se utilizan cargadores. Necesita especificar 'json-loader' en lugar de 'json', véase https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed

 6
Author: Ogglas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-26 14:31:03

Encontró este hilo al intentar (sin éxito) cargar un archivo json local. Esta solución funcionó para mí...

function load_json(src) {
  var head = document.getElementsByTagName('head')[0];

  //use class, as we can't reference by id
  var element = head.getElementsByClassName("json")[0];

  try {
    element.parentNode.removeChild(element);
  } catch (e) {
    //
  }

  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = src;
  script.className = "json";
  script.async = false;
  head.appendChild(script);

  //call the postload function after a slight delay to allow the json to load
  window.setTimeout(postloadfunction, 100)
}

... y se usa así...

load_json("test2.html.js")

...y este es el <head>...

<head>
  <script type="text/javascript" src="test.html.js" class="json"></script>
</head>
 4
Author: TechSpud,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-14 15:48:33

En angular (o cualquier otro marco), puede cargar usando http get Lo uso algo como esto:

this.http.get(<path_to_your_json_file))
 .success((data) => console.log(data));

Espero que esto ayude.

 3
Author: rajkiran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-06 02:24:53
$.ajax({
       url: "Scripts/testingJSON.json",
           //force to handle it as text
       dataType: "text",
            success: function (dataTest) {

                //data downloaded so we call parseJSON function 
                //and pass downloaded data
                var json = $.parseJSON(dataTest);
                //now json variable contains data in json format
                //let's display a few items
                $.each(json, function (i, jsonObjectList) {
                for (var index = 0; index < jsonObjectList.listValue_.length;index++) {
                      alert(jsonObjectList.listKey_[index][0] + " -- " + jsonObjectList.listValue_[index].description_);
                      }
                 });


             }
  });
 2
Author: Karhan Vijay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-23 06:46:06

Si está utilizando un array local para JSON - como mostró en su exmaple en la pregunta (test.json) entonces usted puede es el método parseJSON de jQuery - >

  var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

getJSON se utiliza para obtener JSON de un sitio remoto - no funcionará localmente (a menos que esté utilizando un servidor HTTP local)

 1
Author: ManseUK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-08 10:36:15

json_str = String.raw`[{"name": "Jeeva"}, {"name": "Kumar"}]`;
obj = JSON.parse(json_str);

console.log(obj[0]["name"]);

Hice esto para mi aplicación cordova, como creé un nuevo archivo javascript para el JSON y pegué los datos JSON en String.raw y luego los analicé con JSON.parse

 1
Author: Jeeva,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-01 21:29:26

No he encontrado ninguna solución utilizando la biblioteca de cierre de Google. Así que solo para completar la lista de futuros visitantes, aquí está cómo cargar un JSON desde un archivo local con la biblioteca de cierre:

goog.net.XhrIo.send('../appData.json', function(evt) {
  var xhr = evt.target;
  var obj = xhr.getResponseJson(); //JSON parsed as Javascript object
  console.log(obj);
});
 0
Author: Kenny806,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-26 14:29:17

Un enfoque que me gusta usar es rellenar/envolver el json con un literal de objeto, y luego guardar el archivo con a .extensión de archivo jsonp. Este método también deja su archivo json original (test.json) inalterado, ya que estará trabajando con el nuevo archivo jsonp (test.jsonp) en su lugar. El nombre en el wrapper puede ser cualquier cosa, pero necesita ser el mismo nombre que la función callback que usa para procesar el jsonp. Usaré tu prueba.json publicado como ejemplo para mostrar la adición de la envoltura jsonp para el prueba.archivo jsonp.

json_callback({"a" : "b", "c" : "d"});

A continuación, cree una variable reutilizable con alcance global en su script para contener el JSON devuelto. Esto hará que los datos JSON devueltos estén disponibles para todas las demás funciones de su script en lugar de solo la función de devolución de llamada.

var myJSON;

Luego viene una función simple para recuperar su json por inyección de script. Tenga en cuenta que no podemos usar jQuery aquí para anexar el script al encabezado del documento, ya que IE no admite jQuery .método append. El método jQuery comentado en el código a continuación funcionará en otros navegadores que soportan el .método append. Se incluye como referencia para mostrar la diferencia.

function getLocalJSON(json_url){
    var json_script  = document.createElement('script');
    json_script.type = 'text/javascript';
    json_script.src  = json_url;
    json_script.id   = 'json_script';
    document.getElementsByTagName('head')[0].appendChild(json_script);
    // $('head')[0].append(json_script); DOES NOT WORK in IE (.append method not supported)
}

La siguiente es una función de devolución de llamada corta y simple (con el mismo nombre que el contenedor jsonp) para obtener los datos de resultados json en la variable global.

function json_callback(response){
    myJSON = response;            // Clone response JSON to myJSON object
    $('#json_script').remove();   // Remove json_script from the document
}

Los datos json ahora pueden ser accedidos por cualquier función del script usando notación de puntos. Como ejemplo:

console.log(myJSON.a); // Outputs 'b' to console
console.log(myJSON.c); // Outputs 'd' to console

Este método puede ser un poco diferente de lo que eres acostumbrado a ver, pero tiene muchas ventajas. Primero, el mismo archivo jsonp se puede cargar localmente o desde un servidor usando las mismas funciones. Como beneficio adicional, jsonp ya está en un formato amigable para varios dominios y también se puede usar fácilmente con API de tipo REST.

Concedido, no hay funciones de manejo de errores, pero ¿por qué necesitaría una? Si no puede obtener los datos json utilizando este método, entonces puede apostar a que tiene algunos problemas dentro del propio json, y lo verificaría en una buena Validador JSON.

 0
Author: Epiphany,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-28 11:14:30

Puede poner su json en un archivo javascript. Esto se puede cargar localmente (incluso en Chrome) usando la función getScript() de jQuery.

Map-01.archivo js:

var json = '{"layers":6, "worldWidth":500, "worldHeight":400}'

Main.js

$.getScript('map-01.js')
    .done(function (script, textStatus) {
        var map = JSON.parse(json); //json is declared in the js file
        console.log("world width: " + map.worldWidth);
        drawMap(map);
    })
    .fail(function (jqxhr, settings, exception) {
        console.log("error loading map: " + exception);
    });

Salida:

world width: 500

Observe que la variable json es declarada y asignada en el archivo js.

 0
Author: Victor Stoddard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-24 00:49:21
function readTextFile(srcfile) {
        try { //this is for IE
            var fso = new ActiveXObject("Scripting.FileSystemObject");;
            if (fso.FileExists(srcfile)) {
                var fileReader = fso.OpenTextFile(srcfile, 1);
                var line = fileReader.ReadLine();
                var jsonOutput = JSON.parse(line); 
            }

        } catch (e) {

        }
}

readTextFile("C:\\Users\\someuser\\json.txt");

Lo que hice fue, en primer lugar, desde la pestaña red, registrar el tráfico de red para el servicio, y desde el cuerpo de respuesta, copiar y guardar el objeto json en un archivo local. Luego llame a la función con el nombre de archivo local, debería poder ver el objeto json en jsonOutout arriba.

 0
Author: Feng Zhang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-23 22:29:59

Lo que funcionó para mí es lo siguiente:

Entrada:

http://ip_address//some_folder_name//render_output.html?relative/path/to/json/fie.json

Código Javascript:

<html>
<head>

<style>
pre {}
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
</style>

<script>
function output(inp) {
    document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}

function gethtmlcontents(){
    path = window.location.search.substr(1)
    var rawFile = new XMLHttpRequest();
    var my_file = rawFile.open("GET", path, true)  // Synchronous File Read
    //alert('Starting to read text')
    rawFile.onreadystatechange = function ()
    {
        //alert("I am here");
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                //alert(allText)
                var json_format = JSON.stringify(JSON.parse(allText), null, 8)
                //output(json_format)
                output(syntaxHighlight(json_format));
            }
        }
    }
    rawFile.send(null);
}

function syntaxHighlight(json) {
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

gethtmlcontents();
</script>
</head>
<body>
</body>
</html>
 0
Author: Bishwas Mishra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-24 11:35:59

Si tiene Python instalado en su máquina local (o no le importa instalar uno), aquí hay una solución alternativa independiente del navegador para el problema de acceso a archivos JSON locales que uso:

Transforme el archivo JSON en JavaScript creando una función que devuelva los datos como objeto JavaScript. Luego puede cargarlo con la etiqueta

Aquí viene el código Python

import json


def json2js(jsonfilepath, functionname='getData'):
    """function converting json file to javascript file: json_data -> json_data.js
    :param jsonfilepath: path to json file
    :param functionname: name of javascript function which will return the data
    :return None
    """
    # load json data
    with open(jsonfilepath,'r') as jsonfile:
        data = json.load(jsonfile)
    # write transformed javascript file
    with open(jsonfilepath+'.js', 'w') as jsfile:
        jsfile.write('function '+functionname+'(){return ')
        jsfile.write(json.dumps(data))
        jsfile.write(';}')

if __name__ == '__main__':
    from sys import argv
    l = len(argv)
    if l == 2:
        json2js(argv[1])
    elif l == 3:
        json2js(argv[1], argv[2])
    else:
        raise ValueError('Usage: python pathTo/json2js.py jsonfilepath [jsfunctionname]')
 -4
Author: sytrus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-25 22:27:46