Loading local JSON file

前端 未结 23 1635
悲哀的现实
悲哀的现实 2020-11-22 01:28

I\'m trying to load a local JSON file but it won\'t work. Here is my JavaScript code (using jQuery):

var json = $.getJSON("test.json");
var data = e         


        
相关标签:
23条回答
  • 2020-11-22 01:41

    I haven't found any solution using Google's Closure library. So just to complete the list for future vistors, here's how you load a JSON from local file with Closure library:

    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 讨论(0)
  • 2020-11-22 01:42
    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");
    

    What I did was, first of all, from network tab, record the network traffic for the service, and from response body, copy and save the json object in a local file. Then call the function with the local file name, you should be able to see the json object in jsonOutout above.

    0 讨论(0)
  • 2020-11-22 01:46

    In angular (or any other framework), you can load using http get I use it something like this:

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

    Hope this helps.

    0 讨论(0)
  • 2020-11-22 01:47

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

    I did this for my cordova app, like I created a new javascript file for the JSON and pasted the JSON data into String.raw then parse it with JSON.parse

    0 讨论(0)
  • 2020-11-22 01:48

    An approach I like to use is to pad/wrap the json with an object literal, and then save the file with a .jsonp file extension. This method also leaves your original json file (test.json) unaltered, as you will be working with the new jsonp file (test.jsonp) instead. The name on the wrapper can be anything, but it does need to be the same name as the callback function you use to process the jsonp. I'll use your test.json posted as an example to show the jsonp wrapper addition for the 'test.jsonp' file.

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

    Next, create a reusable variable with global scope in your script to hold the returned JSON. This will make the returned JSON data available to all other functions in your script instead of just the callback function.

    var myJSON;
    

    Next comes a simple function to retrieve your json by script injection. Note that we can not use jQuery here to append the script to the document head, as IE does not support the jQuery .append method. The jQuery method commented out in the code below will work on other browsers that do support the .append method. It is included as a reference to show the difference.

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

    Next is a short and simple callback function (with the same name as the jsonp wrapper) to get the json results data into the global variable.

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

    The json data can now be accessed by any functions of the script using dot notation. As an example:

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

    This method may be a bit different from what you are used to seeing, but has many advantages. First, the same jsonp file can be loaded locally or from a server using the same functions. As a bonus, jsonp is already in a cross-domain friendly format and can also be easily used with REST type API's.

    Granted, there are no error handling functions, but why would you need one? If you are unable to get the json data using this method, then you can pretty much bet you have some problems within the json itself, and I would check it on a good JSON validator.

    0 讨论(0)
  • 2020-11-22 01:49

    I had the same need (to test my angularjs app), and the only way I found is to use require.js:

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

    note: the file is loaded once, further calls will use the cache.

    More on reading files with nodejs: http://docs.nodejitsu.com/articles/file-system/how-to-read-files-in-nodejs

    require.js: http://requirejs.org/

    0 讨论(0)
提交回复
热议问题