How to read an external local JSON file in JavaScript?

前端 未结 22 1937
醉酒成梦
醉酒成梦 2020-11-22 02:53

I have saved a JSON file in my local system and created a JavaScript file in order to read the JSON file and print data out. Here is the JSON file:

{"res         


        
相关标签:
22条回答
  • 2020-11-22 02:57

    You cannot make a AJAX call to a local resource as the request is made using HTTP.

    A workaround is to run a local webserver, serve up the file and make the AJAX call to localhost.

    In terms of helping you write code to read JSON, you should read the documentation for jQuery.getJSON():

    http://api.jquery.com/jQuery.getJSON/

    0 讨论(0)
  • 2020-11-22 02:57

    When in Node.js or when using require.js in the browser, you can simply do:

    let json = require('/Users/Documents/workspace/test.json');
    console.log(json, 'the json obj');
    

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

    0 讨论(0)
  • 2020-11-22 02:57

    Very simple.
    Rename your json file to ".js" instead ".json".

    <script type="text/javascript" src="my_json.js"></script>
    

    So follow your code normally.

    <script type="text/javascript">
    var obj = JSON.parse(contacts);
    

    However, just for information, the content my json it's looks like the snip below.

    contacts='[{"name":"bla bla", "email":bla bla, "address":"bla bla"}]';
    
    0 讨论(0)
  • 2020-11-22 02:58

    You can import It like ES6 module;

    import data from "/Users/Documents/workspace/test.json"
    
    0 讨论(0)
  • 2020-11-22 02:59

    Just use $.getJSON and then $.each to iterate the pair Key /value. Content example for the JSON file and functional code:

        {
            {
                "key": "INFO",
                "value": "This is an example."
            }
        }
    
        var url = "file.json";         
        $.getJSON(url, function (data) {
            $.each(data, function (key, model) {
                if (model.key == "INFO") {
                    console.log(model.value)
                }
            })
        });
    
    0 讨论(0)
  • 2020-11-22 02:59

    You can use XMLHttpRequest() method:

        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var myObj = JSON.parse(this.responseText);
            //console.log("Json parsed data is: " + JSON.stringify(myObj));
           }
        };
    xmlhttp.open("GET", "your_file_name.json", true);
    xmlhttp.send();
    

    You can see the response of myObj using console.log statement(commented out).

    If you know AngularJS, you can use $http:

    MyController.$inject = ['myService'];
    function MyController(myService){
    
    var promise = myService.getJsonFileContents();
    
      promise.then(function (response) {
        var results = response.data;
        console.log("The JSON response is: " + JSON.stringify(results));
    })
      .catch(function (error) {
        console.log("Something went wrong.");
      });
    }
    
    myService.$inject = ['$http'];
    function myService($http){
    
    var service = this;
    
      service.getJsonFileContents = function () {
        var response = $http({
          method: "GET",
          url: ("your_file_name.json")
        });
    
        return response;
      };
    }
    

    If you have the file in a different folder, mention the complete path instead of filename.

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