Domanda

Sto cercando di caricare un file JSON locale ma non funzionerà. Ecco il mio codice JavaScript (usando jQuery:

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

Il file test.json:

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

Nulla viene visualizzato e Firebug mi dice che i dati non sono definiti. In Firebug posso vedere json.responseText Ed è buono e valido, ma è strano quando copio la linea:

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

Nella console di Firebug, funziona e posso accedere ai dati.

Qualcuno ha una soluzione?

È stato utile?

Soluzione

$.getJSON è asincrono, quindi dovresti fare:

$.getJSON("test.json", function(json) {
    console.log(json); // this will show the info it in firebug console
});

Altri suggerimenti

Avevo la stessa necessità (per testare la mia app AngularJS) e l'unico modo che ho trovato è usare Requisite.js:

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

NOTA: il file viene caricato una volta, ulteriori chiamate utilizzeranno la cache.

Maggiori informazioni sulla lettura di file con Nodejs: http://docs.nodejitsu.com/articles/file-system/how-to-read-files-in-nodejs

requisite.js: http://requirejs.org/

Se si desidera consentire all'utente di selezionare il file JSON locale (ovunque sul filesystem), funziona la seguente soluzione.

Utilizza usi FileReader e JSON.Parser (e nessuna 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>

Ecco una buona introduzione su FileReader: http://www.html5rocks.com/en/tutorials/file/dndfiles/

In un modo più moderno, ora puoi usare il API Fetch:

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

Tutti i browser moderni supportano API Fetch. (Internet Explorer no, ma Edge lo fa!)

fonte:

Se stai cercando qualcosa di veloce e sporco, carica i dati nella testa del tuo documento HTML.

data.js

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

Index.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"}
})()

ace.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);
    });
}

Versione 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);
    });
}

Non riesco a credere a quante volte questa domanda sia stata data risposta senza comprendere e/o affrontare il problema con il codice effettivo del poster originale. Detto questo, io stesso sono un principiante (solo 2 mesi di codifica). Il mio codice funziona perfettamente, ma sentiti libero di suggerire eventuali modifiche ad esso. Ecco la soluzione:

//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);

Ecco un modo più breve di scrivere lo stesso codice che ho fornito sopra:

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

Puoi anche usare $ .ajax invece di $ .getjson per scrivere il codice esattamente allo stesso modo:

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

Infine, l'ultimo modo per farlo è avvolgere $ .ajax in una funzione. Non posso prendermi il merito per questo, ma l'ho modificato un po '. L'ho testato e funziona e produce gli stessi risultati del mio codice sopra. Ho trovato questa soluzione qui -> Carica JSON in variabile

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);

Il test.json Il file che vedi nel mio codice sopra è ospitato sul mio server e contiene lo stesso oggetto dati JSON che lui (il poster originale) aveva pubblicato.

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

Sono sorpreso che l'importazione da ES6 non sia stata menzionata (utilizzare con piccoli file)

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

webpack 2 <usa il json-loader come impostazione predefinita per .json File.

https://webpack.js.org/guides/migrating/#json-loader-is-not-required-anymer

Per Dattiloscritto:

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

TS2307 (TS) Impossibile trovare il modulo 'json-carder! ./ Suburbs.json'

Per farlo funzionare ho dovuto dichiarare prima il modulo. Spero che questo risparmia qualche ora per qualcuno.

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

...

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

Se ho provato a omettere loader da json-loader Ho ricevuto il seguente errore da webpack:

Breaking Change: non è più permesso omettere il suffisso '-loader' quando si utilizzano caricatori. È necessario specificare "json caricatore" invece di "json", vedi https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed

Prova è tale modo (ma si noti anche che JavaScript non ha accesso al file system client):

$.getJSON('test.json', function(data) {
  console.log(data);
});

Recentemente D3js è in grado di gestire il file JSON locale.

Questo è il problemahttps://github.com/mbostock/d3/issues/673

Questa è la patch in ordine per D3 per funzionare con i file JSON locali.https://github.com/mbostock/d3/pull/632

Ho trovato questo thread quando provo (senza successo) a caricare un file JSON locale. Questa soluzione ha funzionato per me ...

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)
}

... ed è usato in questo modo ...

load_json("test2.html.js")

... e questo è il <head>...

<head>
  <script type="text/javascript" src="test.html.js" class="json"></script>
</head>

In TypeScript è possibile utilizzare l'importazione per caricare i file JSON locali. Ad esempio, caricando un carattere.json:

import * as fontJson from '../../public/fonts/font_name.json';

Ciò richiede un flag tsconfig - -ResolvejsonModule:

// tsconfig.json

{
    "compilerOptions": {
        "module": "commonjs",
        "resolveJsonModule": true,
        "esModuleInterop": true
    }
}

Per ulteriori informazioni, consultare le note di rilascio di TypeScript: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html

In Angular (o in qualsiasi altro framework), è possibile caricare usando HTTP Get I Uso qualcosa del genere:

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

Spero che sia di aiuto.

$.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_);
                      }
                 });


             }
  });

Se stai usando un array locale per JSON - come hai mostrato nel tuo exmaple nella domanda (test.json), allora puoi il parseJSON Metodo di jQuery ->

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

getJSON viene utilizzato per ottenere JSON da un sito remoto: non funzionerà a livello locale (a meno che tu non stia utilizzando un server HTTP locale)

Non ho trovato alcuna soluzione utilizzando la libreria di chiusura di Google. Quindi, solo per completare l'elenco per i futuri visite, ecco come si carica un JSON dal file locale con la libreria di chiusura:

goog.net.XhrIo.send('../appData.json', function(evt) {
  var xhr = evt.target;
  var obj = xhr.getResponseJson(); //JSON parsed as Javascript object
  console.log(obj);
});

Un approccio che mi piace usare è quello di sfogliare/avvolgere il JSON con un oggetto letterale, quindi salvare il file con un'estensione del file .JSONP. Questo metodo lascia anche il tuo file JSON originale (test.json), poiché lavorerai invece con il nuovo file JSONP (test.jsonp). Il nome sul wrapper può essere qualsiasi cosa, ma deve essere lo stesso nome della funzione di callback che usi per elaborare JSONP. Userò il tuo test.json pubblicato come esempio per mostrare l'aggiunta di wrapper JSONP per il file "test.jsonp".

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

Successivamente, crea una variabile riutilizzabile con l'ambito globale nella sceneggiatura per tenere il JSON restituito. Ciò renderà i dati JSON restituiti disponibili per tutte le altre funzioni nel tuo script invece della funzione di callback.

var myJSON;

Successivamente arriva una semplice funzione per recuperare il tuo JSON mediante iniezione di script. Si noti che non possiamo usare JQuery qui per aggiungere lo script alla testa del documento, poiché IE non supporta il metodo JQuery .Append. Il metodo jQuery commentato nel codice seguente funzionerà su altri browser che supportano il metodo .Append. È incluso come riferimento per mostrare la differenza.

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 prossima è una funzione di callback breve e semplice (con lo stesso nome del wrapper JSONP) per ottenere i dati dei risultati JSON nella variabile globale.

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

I dati JSON sono ora accessibili da qualsiasi funzioni dello script usando la notazione Dot. Come esempio:

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

Questo metodo può essere un po 'diverso da quello che sei abituato a vedere, ma ha molti vantaggi. Innanzitutto, lo stesso file JSONP può essere caricato localmente o da un server utilizzando le stesse funzioni. Come bonus, JSONP è già in un formato amichevole a dominio e può anche essere facilmente utilizzato con le API di tipo REST.

Certo, non ci sono funzioni di gestione degli errori, ma perché dovresti averne uno? Se non sei in grado di ottenere i dati JSON utilizzando questo metodo, puoi praticamente scommettere che hai alcuni problemi all'interno del JSON stesso e lo controllerei su un buon validatore JSON.

Puoi mettere il tuo JSON in un file JavaScript. Questo può essere caricato localmente (anche in Chrome) usando jQuery getScript() funzione.

file map-01.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);
    });

produzione:

world width: 500

Si noti che la variabile JSON è dichiarata e assegnata nel file JS.

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

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

L'ho fatto per la mia app Cordova, come se avessi creato un nuovo file JavaScript per JSON e incollato i dati JSON String.raw Quindi analizzalo con JSON.parse

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");

Quello che ho fatto è stato, prima di tutto, dalla scheda Network, registrare il traffico di rete per il servizio e dal corpo della risposta, copiare e salvare l'oggetto JSON in un file locale. Quindi chiama la funzione con il nome del file locale, dovresti essere in grado di vedere l'oggetto JSON in JSONOUTOUT sopra.

Quello che ha funzionato per me è il seguente:

Ingresso:

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

Codice 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>

Quello che ho fatto è stato modificare un po 'il file JSON.

myfile.json => myfile.js

Nel file JSON, (rendilo una variabile JS)

{name: "Whatever"} => var x = {name: "Whatever"}

Alla fine,

export default x;

Quindi,

import JsonObj from './myfile.js';

Se hai installato Python sulla macchina locale (o non ti dispiace installarne uno), ecco una soluzione alternativa indipendente dal browser per il problema di accesso al file JSON locale che utilizzo:

Trasforma il file JSON in un JavaScript creando una funzione che restituisce i dati come oggetto JavaScript. Quindi puoi caricarlo conu003Cscript> tag and call the function to get the data you want.

Ecco che arriva Il codice 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]')
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top