How to parse a JSON file without web request or web server?

前端 未结 5 780
旧巷少年郎
旧巷少年郎 2021-01-21 21:08

Looking to build a work-around of the following.

$.getJSON(\'myfile.json\', function (data) {
    showAll(data);
});

I want to avoid using a we

相关标签:
5条回答
  • 2021-01-21 21:08

    AJAX is about making asynchronous HTTP requests. You need a web server to make those requests and receive those responses. JQuery's .get() method won't let you avoid a web server.

    The only way I can think of would be to include an iframe in your code and set the source of the iframe to your resource that includes the JSON. Then, you could use JSON.parse() on the contents of the iframe.

    0 讨论(0)
  • 2021-01-21 21:17

    If you have a permission correctly, you can get the file using <script> tag.

    in html:

    <script src="./favs.js"></script>
    <script src="./script.js"></script>
    

    in favs.js:

    var favs = [
        { url: 'http://google.com' },
        { url: 'http://stackoverflow.com' }
    ];
    

    in script.js:

    console.log(favs); // you can use favs as global variables
    

    Otherwise, if you want to use ajax call such as $.getJSON(), you should have a webserver somehow.


    Additionally, you can load js file dynamically. May you can use the code below for example:

    function loadScript(path, onload) {
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = path;
      var s = document.getElementsByTagName('script')[0];
      s.parentNode.insertBefore(script, s);
      if(onload) s.onload = onload;
    }
    
    0 讨论(0)
  • 2021-01-21 21:19

    Simple, fast, but bad for real project solution:

    1. Rename myfile.json to data.js (name doesn't matter).
    2. Create a variable in data.js and initialize it with your json var myData = {...your json...}
    3. Add <script src="./data.js"></script> to your html file.
    4. Now you can use myData variable from javascript with all data.

    This solution is bad because you add a new variable in global scope and browser would still make a http request to get this .js file.

    Also, If you want to make ajax requests to your local files, you can use http server. Take a look at very simple node js http-server.

    0 讨论(0)
  • 2021-01-21 21:19

    This would be a 3 step process.

    Move the JSON file into a folder with you other web pages

    In the JSON file, give the obejct a name i.e. var data = {...};

    In the file that you wan to use it just call it with the <script src='myJSON.js'></script>

    0 讨论(0)
  • If it is static JSON resource, why make another network request. Network is expensive. You can change to .js and include the file in the page.

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