422

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:

{"resource":"A","literals":["B","C","D"]}

Let’s say this is the path of the JSON file: /Users/Documents/workspace/test.json.

Could anyone please help me write a simple piece of code to read the JSON file and print the data in JavaScript?

Mod
  • 5,091
  • 7
  • 28
  • 47
  • possible duplicate of [How can I get javascript to read from a .json file?](http://stackoverflow.com/questions/6711002/how-can-i-get-javascript-to-read-from-a-json-file) – Mindbreaker Oct 31 '13 at 12:07
  • it may pay off also specifying which JavaScript run-time is in question ... – Yordan Georgiev Jul 12 '20 at 06:43

28 Answers28

235

For reading the external Local JSON file (data.json) using javascript, first create your data.json file:

data = '[{"name" : "Ashwin", "age" : "20"},{"name" : "Abhinandan", "age" : "20"}]';

Then,

  1. Mention the path of the json file in the script source along with the javascript file

     <script type="text/javascript" src="data.json"></script>
     <script type="text/javascript" src="javascript.js"></script>
    
  2. Get the Object from the json file

     var mydata = JSON.parse(data);
     alert(mydata[0].name);
     alert(mydata[0].age);
     alert(mydata[1].name);
     alert(mydata[1].age);
    

For more information, see this reference.

Ashfedy
  • 3,467
  • 2
  • 12
  • 7
  • 26
    This works if you can modify the file, or if the file does not have proper JSON as its contents. For instance the sample content for `data.json` above does not pass validation: http://jsonlint.com/ because it is really JavaScript. Dropping the wrapping single quotes would turn it into pure JavaScript. – Jason Aller Jun 24 '14 at 05:18
  • 3
    **Note:** `JSON.parse` is not supported in some older browsers (looking at you IE). See [MDN's Browser Compatibility table for `window.JSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON#Browser_compatibility). – Sumner Evans Apr 14 '15 at 03:49
  • Shouldn't JSON.parse(data); not work because data is a string? – call-me Apr 16 '15 at 16:26
  • 480
    This is not a correct answer. The example in the answer is not loading a json file. It is actually just loading another javascript file which stores some hardcoded json as a variable named `data`. If you removed the string quotes from around the json in `data.json` you wouldn't even need to use `JSON.parse`. The question is how to load a JSON file not how to hardcode JSON into another javascript file and then load it. – wuliwong Jun 19 '15 at 15:04
  • 1
    `JSON.parse(window.data);` would provide better information of the `scope` of the `data` variable. – Aakash Apr 05 '16 at 10:51
  • 1
    It does not work for me, or I don't know how to make use of the above information. – Nikos Alexandris Aug 11 '16 at 20:00
  • You can convert any JSON to .js file with [json2js](https://github.com/sanxofon/json_html_viewer/blob/master/json2js/json2jsondata.py) – lalengua May 05 '18 at 23:36
  • 1
    Worked for me after making a couple of modifications. First, changed data.json to data.js and second, for multi line json I used ` as mentioned [here](https://stackoverflow.com/a/805113/4457330) – Afsan Abdulali Gujarati May 17 '18 at 14:27
  • hi in your script u used data.json does that mean to access that file in your json you just refer to it as data? – preston Jul 09 '18 at 02:43
  • 2
    The `` should really be ``. Notice it is a javascript file. – Benny Oct 14 '19 at 14:59
  • @wuliwong if you remove the quotes aroung the array and remove the json.parse, it works. But what do you import then? A mix of `json/js`, i.e. a js array from a json file? – Timo Aug 18 '20 at 12:54
  • 1
    Although this is not a correct answer, it was very helpful to me, because it made me realize "doh, i can just use js instead of json". I have control of the data, so I can change it to be code instead easily. – John Henckel Dec 10 '20 at 15:17
  • This not a correct answer. data.json is not a json file but a JavaScript file. Even browser cannot read this read as json. Browsers show this error "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data" . – Nabeel Jun 18 '21 at 02:39
  • No. Does not address the question. Changes the parameters of the situation to answer a similar question. – Ken Ingram Mar 13 '22 at 23:20
174

The loading of a .json file from harddisk is an asynchronous operation and thus it needs to specify a callback function to execute after the file is loaded.

function readTextFile(file, callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
        if (rawFile.readyState === 4 && rawFile.status == "200") {
            callback(rawFile.responseText);
        }
    }
    rawFile.send(null);
}

//usage:
readTextFile("/Users/Documents/workspace/test.json", function(text){
    var data = JSON.parse(text);
    console.log(data);
});

This function works also for loading a .html or .txt files, by overriding the mime type parameter to "text/html", "text/plain" etc.

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
Stano
  • 8,749
  • 6
  • 30
  • 44
  • 24
    This is a very bad practice! In Google Chrome, you can't make an XmlHttpRequest to a local resource. – mhaseeb Mar 05 '17 at 19:49
  • 12
    @mhaseeb You can (even now, in the future), if the resource has the same domain/protocol as the requesting system (which this will, since it is local). Look up CORS. – GreySage Mar 21 '17 at 20:41
  • 19
    on trying this with current Chrome, I get "Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https." - so no file protocol, which is implied here @GreySage – eis Jun 24 '18 at 13:20
  • 2
    XMLHttpRequest.status returns a numeric value. This only works because javascript is doing stuff in the background to make your code not die. Should read as follows: rawFile.status === 200 – user3044394 Nov 24 '18 at 07:46
  • 1
    You can also set `rawFile.responseType = 'json';` so that it parses the json object automatically, just make sure to pass `rawFile.response` instead of `rawFile.responseText` to the callback. – Ignat Dec 28 '19 at 07:51
  • Perfect! Best native solution so far. – Yatix May 23 '21 at 08:43
  • @eis In chrome, if you open it with the flag --allow-file-access-from-files, then you will not get the error, and the code works. Not sure what the security implications of this are though. – s6mike Aug 10 '22 at 02:14
  • The "data" here is still not accessible by the calling context but hidden in the function. How to make it availible to the script? – Fred Nov 25 '22 at 07:07
122

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/

Chris Pickford
  • 8,642
  • 5
  • 42
  • 73
  • 2
    Could you please guide me how I can run a local server in this case? What do I need to do in order to get the local server run? – Mod Oct 31 '13 at 12:08
  • 2
    What environment are you using? Windows? Linux? – Chris Pickford Oct 31 '13 at 12:10
  • You could use [Yeoman](http://yeoman.io/). That allows you to scaffold your project, and provides you with local file development server. I've found it very handy. You'll need to install `nodejs` and `git` as it mentions on their `getting started` sections. – Andy Oct 31 '13 at 12:11
  • I am having Tomcat. Does that help to do this task, Chris? – Mod Oct 31 '13 at 12:15
  • I searched for `mac local webserver` and found this easy guide: http://osxdaily.com/2012/09/02/start-apache-web-server-mac-os-x/ – Chris Pickford Oct 31 '13 at 12:16
  • Tomcat is a Java application server and is massively overkill for your use case. – Chris Pickford Oct 31 '13 at 12:16
  • 35
    This is true only for AJAX: under Chrome and using HTML5's File API I already did it. The question did not ask about AJAX. – lauhub Oct 31 '13 at 12:16
  • 13
    If you have python installed you can use command line `python -m SimpleHTTPServer 8888` and open `http://localhost:8888/` in your browser (Windows or Mac). `8888` is the port and can be changed. – geotheory Dec 22 '14 at 21:46
  • @ChrisPickford: Following the link in the answer, one can see it's possible to specify a local file as a JSON location. However, this causes XSS issues. So, unfortunately, running a web server, or hacking one's browser security settings, does seem to be the easiet way. – Michael Scheper Jun 30 '15 at 19:59
  • The question is not specifically about a web application. It is fine to run javascript on the command-line. – Wheezil Jan 13 '18 at 18:15
  • it is a contradiction, you said: You cannot make a AJAX call to a local resource as the request is made using HTTP. but description of the link above says: Description: Load JSON-encoded data from the server using a GET HTTP request. – Ezequiel De Simone Aug 28 '18 at 20:19
  • 4
    To update @geotheory's comment, with Python 3 the command is `python -m http.server 8888` – Marc Stober May 12 '19 at 14:58
  • 2
    Also, the PHP alternative to the Python method: `php -S 127.0.0.1:8888` – geotheory May 12 '19 at 19:51
76

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.

Yordan Georgiev
  • 5,114
  • 1
  • 56
  • 53
musicformellons
  • 12,283
  • 4
  • 51
  • 86
69

Using the Fetch API is the easiest solution:

fetch("test.json")
  .then(response => response.json())
  .then(json => console.log(json));

It works perfect in Firefox, but in Chrome you have to customize security setting.

Alex Glinsky
  • 3,346
  • 1
  • 17
  • 14
  • 4
    When I try this one I got following error: (node:2065) UnhandledPromiseRejectionWarning: Error: only absolute urls are supported – Jangid Oct 21 '19 at 16:03
38
  1. First, create a json file. In this example my file is words.json

[{"name":"ay","id":"533"},
{"name":"kiy","id":"33"},
{"name":"iy","id":"33"},
{"name":"iy","id":"3"},
{"name":"kiy","id":"35"},
{"name":"kiy","id":"34"}]
  1. And here is my code i.e,node.js. Note the 'utf8' argument to readFileSync: this makes it return not a Buffer (although JSON.parse can handle it), but a string. I am creating a server to see the result...

var fs=require('fs');
var data=fs.readFileSync('words.json', 'utf8');
var words=JSON.parse(data);
var bodyparser=require('body-parser');
console.log(words);
var express=require('express');

var app=express();

var server=app.listen(3030,listening);

function listening(){
console.log("listening..");
}
app.use(express.static('website'));
app.use(bodyparser.urlencoded({extended:false}));
app.use(bodyparser.json());
  1. When you want to read particular id details you can mention the code as..

 app.get('/get/:id',function(req,res){
 
var i;
   
 for(i=0;i<words.length;++i)
 {
 if(words[i].id==req.params.id){
 res.send(words[i]);
 }
}
console.log("success");
   
});
  1. When you entered in url as localhost:3030/get/33 it will give the details related to that id....and you read by name also. My json file has simillar names with this code you can get one name details....and it didn't print all the simillar names

 app.get('/get/:name',function(req,res){
 
var i;
   
 for(i=0;i<words.length;++i)
 {
 if(words[i].id==req.params.name){
 res.send(words[i]);
 }
}
console.log("success");
   
});
  1. And if you want to read simillar name details, you can use this code.

app.get('/get/name/:name',function(req,res){
word = words.filter(function(val){
  return val.name === req.params.name;
});
res.send(word);
    
 console.log("success");
   
});
  1. If you want to read all the information in the file then use this code below.

app.get('/all',sendAll);
 
 function sendAll(request,response){
 response.send(words);

 }
 
Zelo101
  • 110
  • 2
  • 6
Syed Ayesha Bebe
  • 1,797
  • 1
  • 15
  • 26
30

You can import It like ES6 module;

import data from "/Users/Documents/workspace/test.json"
Serhan C.
  • 1,152
  • 1
  • 12
  • 10
22


As many people mentioned before, this doesn't work using an AJAX call. However, there's a way around it. Using the input element, you can select your file.

The file selected (.json) need to have this structure:

[
    {"key": "value"},
    {"key2": "value2"},
    ...
    {"keyn": "valuen"},
]


<input type="file" id="get_the_file">

Then you can read the file using JS with FileReader():

document.getElementById("get_the_file").addEventListener("change", function() {
  var file_to_read = document.getElementById("get_the_file").files[0];
  var fileread = new FileReader();
  fileread.onload = function(e) {
    var content = e.target.result;
    // console.log(content);
    var intern = JSON.parse(content); // Array of Objects.
    console.log(intern); // You can index every object
  };
  fileread.readAsText(file_to_read);
});
Franco Gil
  • 323
  • 3
  • 11
Sarah
  • 460
  • 4
  • 9
  • where do you put in the name of your file? – shieldgenerator7 Aug 22 '19 at 00:16
  • 3
    In this case, the user has to select the file themselves because of the CORS policy, which basically prevents the developer of the web page from grabbing data they're not supposed to(ex. I could take their private files, I could make a GET request to a potentially bad script and run it without the user's permission). The CORS policy makes this kind of stuff a pain to deal with without any kind of backend, but it makes the user safer. If you wanted to actually open a file, you'd have to run a web server which can manage those requests. – Sarah Dec 30 '19 at 22:37
15

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"}]';
12

Depending on your browser, you may access to your local files. But this may not work for all the users of your app.

To do this, you can try the instructions from here: http://www.html5rocks.com/en/tutorials/file/dndfiles/

Once your file is loaded, you can retrieve the data using:

var jsonData = JSON.parse(theTextContentOfMyFile);
lauhub
  • 894
  • 1
  • 15
  • 27
10

If you are using local files, why not just packade the data as a js object?

data.js

MyData = { resource:"A",literals:["B","C","D"]}

No XMLHttpRequests, no parsing, just use MyData.resource directly

Ali BAGHO
  • 358
  • 6
  • 17
user7394313
  • 522
  • 4
  • 4
  • 3
    Okay, but may you please complete MyData.resource part for javascript to show its usage to be more clear. Thanks. – Bay Sep 22 '19 at 11:35
9

2021 solution (works in Chrome 91+)

The JS file where you're importing JSON file should be a module:

<script type="module" src="script.js"></script>

Then inside script.js import your json file:

import data from "./data.json" assert { type: "json" };

You can check that data is loaded with console.log(data)

Source

Vlad Volkov
  • 183
  • 3
  • 5
  • This appears to [require setting a variable](https://stackoverflow.com/questions/42237388/syntaxerror-import-declarations-may-only-appear-at-top-level-of-a-module) to work in firefox. Some indication that it was [slated for Firefox 96](https://bugzilla.mozilla.org/show_bug.cgi?id=1736060), but I'm running 96, and it's not working here yet. Beware of this if looking for a production solution. – robm Feb 06 '22 at 02:07
  • 4
    Got error: "Access to script at 'file:///C:/Users/user/Desktop/load-json.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.", on Chrome 98. Similar CORS error on Firefox 97 – Rami Sedhom Feb 22 '22 at 13:28
  • No. Even the source you linked is poorly documented. No example of working code; No explanation for troubleshooting. This is not helpful. – Ken Ingram Mar 13 '22 at 23:20
  • Duplicates https://stackoverflow.com/a/57740731/2428640 (two years later). – Pascal de Kloe Jun 26 '22 at 16:47
7

You can do this with fetch() with the help of async await. It is the latest and safest way of fetching data from url.

const url = "../asset/videoData.json";

const fetchJson = async () => {
  try {
    const data = await fetch(url);
    const response = await data.json();  
  } catch (error) {
    console.log(error);
  }
 };

You can use this for fetching data from external url also.

Tushar Pramanik
  • 171
  • 2
  • 4
6

All the solutions above mentioned will work only when you have a local webserver running on your local host. If you want to achieve this with out a web server, you might need to put in some manual effort by uploading the JSON file using file upload control. The browser will not offer this functionality with out a local server because of security risks.

You can parse the uploaded file with out a local webserver as well. Here is the sample code I have achieved a solution similar problem.

 <div id="content">
    <input type="file" name="inputfile" id="inputfile">
    <br>

    <h2>
        <pre id="output"></pre>
    </h2>
</div>
<script type="text/javascript">
    document.getElementById('inputfile')
        .addEventListener('change', function () {

            let fileReader = new FileReader();
            fileReader.onload = function () {
                let parsedJSON = JSON.parse(fileReader.result);
                console.log(parsedJSON);
                // your code to consume the json                    
            }
            fileReader.readAsText(this.files[0]);
        }) 
</script>

In my case I want to read a local JSON file and show it in a html file on my desktop, that's all I have to do.

Note: Don't try to automate the file uploading using JavaScript, even that's also not allowed due the same security restrictions imposed by browsers.

Ravikumar B
  • 779
  • 1
  • 14
  • 25
5

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

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.

Maharshi Rawal
  • 242
  • 1
  • 7
  • 18
2

Since you have a web application, you may have a client and a server.

If you have only your browser, and you want to read a local file from a javascript that is running in your browser, that means that you have only a client. For security reasons, the browser should not let you do such thing.

However, as lauhub explained above, this seems to work:

http://www.html5rocks.com/en/tutorials/file/dndfiles/

Other solution is to setup somewhere in your machine a web server (tiny in windows or monkey in linux) and with an XMLHttpRequest or D3 library, request the file from the server and read it. The server will fetch the file from the local filesystem, and serve it to you through the web.

Antoni
  • 2,542
  • 20
  • 21
1

If you could run a local web server (as Chris P suggested above), and if you could use jQuery, you could try http://api.jquery.com/jQuery.getJSON/

Community
  • 1
  • 1
Nicolae Olariu
  • 2,487
  • 2
  • 18
  • 30
1

I liked what Stano/Meetar commented above. I use it to read .json files. I have expanded their examples using Promise. Here is the plunker for the same. https://plnkr.co/edit/PaNhe1XizWZ7C0r3ZVQx?p=preview

function readTextFile(file, callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
        if (rawFile.readyState === 4 && rawFile.status == "200") {
            callback(rawFile.responseText);
        }
    }
    rawFile.send(null);
}

//usage:
// readTextFile("DATA.json", function(text){
//     var data = JSON.parse(text);
//     console.log(data); 
// });


var task1 = function (){
  return new Promise (function(resolve, reject){
    readTextFile("DATA.json", function(text){
    var data = JSON.parse(text);
    console.log('task1 called');
    console.log(data);
    resolve('task1 came back');
    }); 
  });
};

var task2 = function (){
  return new Promise (function(resolve, reject){
    readTextFile("DATA2.json", function(text){
    var data2 = JSON.parse(text);
    console.log('task2 called');
    console.log(data2);
    resolve('task2 came back');
    });
  });
}

Promise.race([task1(), task2()])
       .then(function(fromResolve){
          console.log(fromResolve); 
       });

The reading of JSON can be moved into another function, for DRY; but the example here is more of showcasing how to use promises.

Plankton
  • 388
  • 3
  • 13
  • Has tried your project from plunker it clearly shows cross origin error similar to other solutions but dont know how prunker works – Ajit Hogade Feb 23 '21 at 16:38
0

You must create a new XMLHttpRequest instance and load the contents of the json file.

This tip work for me (https://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript):

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

 loadJSON(function(response) {
    // Parse JSON string into object
    var actual_JSON = JSON.parse(response);
 });
rodrigomelo
  • 59
  • 1
  • 1
  • 3
  • Still works on Firefox but doesn't on Chrome: `Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https`. You could use [json2js](https://github.com/sanxofon/json_html_viewer/blob/master/json2js/json2jsondata.py) to convert any JSON to .JS file. – lalengua May 05 '18 at 23:27
0

You can use d3.js to import JSON files. Just call d3 on your html body:

<script src="https://d3js.org/d3.v5.min.js"></script>

Then put this on your js scripts:

  d3.json("test.json").then(function(data_json) {
         //do your stuff
  })
mmdfl
  • 61
  • 8
0

Using jQuery and ajax works fine to read JSON file and manipulate the data

    $(document).ready(function () {
        $.ajax({
            url: 'country.json',
            type: 'GET',
            dataType: 'json',
            success: function (code, statut) {
                for (let i in code) {
                    console.log(i)
                           }

            }
        });
    });
L3xpert
  • 1,109
  • 1
  • 10
  • 19
0

Just wanted to provide another method since all above looked too complicated to me. Works for me on my Chrome Version 95.0.4638.54.

Just quick and dirty js code

//read json document and remove the new line
var object = JSON.stringify(document.activeElement.textContent.replaceAll('\n',''));

//parse the string to json... don't know why but oje json.parse is not enough..
var json = JSON.parse(JSON.parse(object));

//read your json
json.items[0].contactInfo.firstName

//enjoy

Test json:

{
  "items": [
    {
      "type": "test1",
      "id": "test1",
      "name": "test1",
      "entityId": "test1",
      "active": true,
      "contactInfo": {
        "company": "test1",
        "firstName": "test1",
        "email": "test1"
      }
    },
    {
      "type": "test2",
      "id": "test2",
      "name": "test2",
      "entityId": "test2",
      "active": true,
      "contactInfo": {
        "company": "test2",
        "firstName": "test2",
        "email": "test2"
        }
    }
    ]
}

enter image description here

-1

You could use D3 to handle the callback, and load the local JSON file data.json, as follows:

<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>

<script>
  d3.json("data.json", function(error, data) {
    if (error)
      throw error;
    console.log(data);
  });
</script>
Alex
  • 12,078
  • 6
  • 64
  • 74
-1

One simple workaround is to put your JSON file inside a locally running server. for that from the terminal go to your project folder and start the local server on some port number e.g 8181

python -m SimpleHTTPServer 8181

Then browsing to http://localhost:8181/ should display all of your files including the JSON. Remember to install python if you don't already have.

ewalel
  • 1,932
  • 20
  • 25
-1

Turn the JSON file into a .js file and assign the json to a variable or const, then refer to it in your main javascript file.

  • How about an example. – Ken Ingram Mar 13 '22 at 23:13
  • 1
    JSON is not the same as js objects – qwr Jul 07 '22 at 18:03
  • Assuming the question is about node.js: 1. If the json file is e.g. uploaded via a web-form and therefore dynamic, you shouldn't rename it and add some commonjs export statements, because that would be a complicated workaround to an otherwise easy problem that potentially causes injection vulnerabilities. 2. you can already use `require` on json files our of the box – sezanzeb Nov 28 '22 at 15:42
-2

I took Stano's excellent answer and wrapped it in a promise. This might be useful if you don't have an option like node or webpack to fall back on to load a json file from the file system:

// wrapped XMLHttpRequest in a promise
const readFileP = (file, options = {method:'get'}) => 
  new Promise((resolve, reject) => {
    let request = new XMLHttpRequest();
    request.onload = resolve;
    request.onerror = reject;
    request.overrideMimeType("application/json");
    request.open(options.method, file, true);
    request.onreadystatechange = () => {
        if (request.readyState === 4 && request.status === "200") {
            resolve(request.responseText);
        }
    };
    request.send(null);
});

You can call it like this:

readFileP('<path to file>')
    .then(d => {
      '<do something with the response data in d.srcElement.response>'
    });
ewilan
  • 638
  • 6
  • 16
-3

I have read the above and notice that usually in projects someone wants to have more than one json file to be loaded. In some cases a gazilion and in some cases "a directory of json files" (of which you would otherwise have to generate a list first to be able to download each of them). It get get messy if this is all over the project. And it can be a hassle if there are many relations between data in the json files.

Obviously that can all be done with the above methods, either making them .js files or retrieving them via some sort of local fetching.

However an alternative (if you do not want a server side solution with tiers) that I found useful is to first load all your data in a Sql Lite database. This makes managing more data also a bit easier and you only have one file with all your data etc...

Then you use web assembly to load your sqlite database and then you can use regular queries to query your data client-side. So this can all be done client-side

Here is an example: https://github.com/projectje/bookmarks-sync-sql-cogmios/blob/master/src/html/index.ts (typescript file that gets compiled to client-side solution).

In a read/write site you can deliver a sqlite database per user that you cache so that the data is unique for that user , etc.

ref: https://github.com/sql-js/sql.js

edelwater
  • 2,650
  • 8
  • 39
  • 67