Loading local JSON file

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

    Recently D3js is able to handle local json file.

    This is the issue https://github.com/mbostock/d3/issues/673

    This is the patch inorder for D3 to work with local json files. https://github.com/mbostock/d3/pull/632

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

    What I did was editing the JSON file little bit.

    myfile.json => myfile.js

    In the JSON file, (make it a JS variable)

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

    At the end,

    export default x;

    Then,

    import JsonObj from './myfile.js';

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

    In TypeScript you can use import to load local JSON files. For example loading a font.json:

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

    This requires a tsconfig flag --resolveJsonModule:

    // tsconfig.json
    
    {
        "compilerOptions": {
            "module": "commonjs",
            "resolveJsonModule": true,
            "esModuleInterop": true
        }
    }
    

    For more information see the release notes of typescript: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html

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

    If you want to let the user select the local json file (anywhere on the filesystem), then the following solution works.

    It uses uses FileReader and JSON.parser (and no 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>
    

    Here is a good intro on FileReader: http://www.html5rocks.com/en/tutorials/file/dndfiles/

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

    If you are using a local array for JSON - as you showed in your example in the question (test.json) then you can is the parseJSON() method of JQuery ->

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

    getJSON() is used for getting JSON from a remote site - it will not work locally (unless you are using a local HTTP Server)

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

    ES5 version

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

    ES6 version

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

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