Loading local JSON file

前端 未结 23 1598
悲哀的现实
悲哀的现实 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:37

    Try is such way (but also please note that JavaScript don't have access to the client file system):

    $.getJSON('test.json', function(data) {
      console.log(data);
    });
    
    0 讨论(0)
  • 2020-11-22 01:38
    $.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_);
                          }
                     });
    
    
                 }
      });
    
    0 讨论(0)
  • 2020-11-22 01:38

    If you have Python installed on your local machine (or you don't mind install one), here is a browser-independent workaround for local JSON file access problem that I use:

    Transform the JSON file into a JavaScript by creating a function that returns the data as JavaScript object. Then you can load it with <script> tag and call the function to get the data you want.

    Here comes the Python code

    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]')
    
    0 讨论(0)
  • 2020-11-22 01:39

    I'm surprised import from es6 has not been mentioned (use with small files)

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

    webpack 2< uses the json-loader as default for .json files.

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

    For TypeScript:

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

    TS2307 (TS) Cannot find module 'json-loader!./suburbs.json'

    To get it working I had to declare the module first. I hope this will save a few hours for someone.

    declare module "json-loader!*" {
      let json: any;
      export default json;
    }
    
    ...
    
    import test from 'json-loader!./test.json';
    

    If I tried to omit loader from json-loader I got the following error from webpack:

    BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders. You need to specify 'json-loader' instead of 'json', see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed

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

    If you're looking for something quick and dirty just load the data in the head of your HTML document.

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

    I should mention that your heap size (in Chrome) is about 4GBs, so if your data is larger than that you should find another method. If you want to check another browser try this:

    window.performance.memory.jsHeapSizeLimit / 1024 / 1024 / 1024 + " GBs"
    // "4.046875 GBs"
    
    0 讨论(0)
  • 2020-11-22 01:41

    What worked for me is the following:

    Input:

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

    Javascript Code:

    <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 讨论(0)
提交回复
热议问题