JSON is a popular data format used by web developers to transfer data from browser to web server and vice versa. Typically, web pages retrieve JSON data or file from web server and display its contents. But sometimes you may need to load local JSON file on your web browser.
How to Load Local JSON File
You can easily load local JSON file using jQuery, instead of plain JavaScript, as it gets a little complicated. Here is a simple code snippet to load local JSON file /home/ubuntu/test.json. jQuery provides getJSON() file that allows you to retrieve local as well as remote JSON files as well as data.
$.getJSON("/home/ubuntu/test.json", function(json) { console.log(json); // this will show the info in browser console });
This will show the file contents in file console.
But please note a few things before you implement the above code. By default, browsers are not supposed to have access to local file system. So most modern browsers like Chrome, Firefox & Edge will block the above code and not even give an error in console.
To overcome this, you need to open the browser with –allow-file-access-from-files flag enabled. For example, in Windows, you need to run the following command to do this.
> "C:\PathTo\Chrome.exe" --allow-file-access-from-files
Since it leaves your browser open to read & write files to local system, when you open Chrome as shown above, you must avoiding accessing any other website since it can contain malicious code to access your local file system.
Secondly, it is a lot safer to simply load the local file on a local HTTP server and access it that way. In this setup, your web browser can be opened normally without enabling the flag shown above.
In this article, we have learnt how to load local JSON file. You can also use it to load other local files. But please be careful before doing this, due to the reasons mentioned above.
Also read:
How to Show Loading Spinner in jQuery
How to Convert String to Boolean in JS
How to Convert Decimal to Hexadecimal in JS
How to Add 30 Minutes to Date in JS
How to Measure Time Taken By JS Function
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.