-1

I want to read a JSON-File from local with JavaScript. The file's name is "posts.json" and the content is the following:

{
    "post0": "<empty>", //1
    "post1": "<empty>", //2
    "post2": "<empty>", //3
    "post3": "<empty>", //4
    "post4": "<empty>", //5
    "post5": "<empty>", //6
    "post6": "<empty>", //7
    "post7": "<empty>", //8
    "post8": "<empty>", //9
    "post9": "<empty>" //10
}

Futher I want to edit the JSON-File in the code.

How can I do it?

Regards Christian

Christian01
  • 307
  • 1
  • 5
  • 19

4 Answers4

1

For reading a JSON file you can do something like this:

const fs = require('fs');

let rawdata = fs.readFileSync('posts.json');
let posts = JSON.parse(rawdata);
console.log(posts);

For editing a JSON file you can do something like this:

const fs = require('fs');

let posts = { 
    "post0": "<empty>", //1
    "post1": "<empty>", //2
    "post2": "<empty>", //3
    "post3": "<empty>", //4
    "post4": "<empty>", //5
    "post5": "<empty>", //6
    "post6": "<empty>", //7
    "post7": "<empty>", //8
    "post8": "<empty>", //9
    "post9": "<empty>" //10
};

fs.writeFile('posts.json', posts, (err) => {
    if (err) throw err;
    console.log('Data written to file');
});

If you want to read files on the client-side, you can use the FileReader API:

HTML:

<input type="file" id="file" name="file" enctype="multipart/form-data"/>

JS:

document.getElementById('file').addEventListener('change', readFile, false);

function readFile (evt) {
    var files = evt.target.files;
    var file = files[0];           
    var reader = new FileReader();
    reader.onload = function(event) {
       console.log(event.target.result);            
    }
    reader.readAsText(file)
 }
Megh Agarwal
  • 216
  • 1
  • 7
  • Hey Megh, thank you for your help. It doesn't work. I get the following error: Uncaught TypeError: fs.readFileSync is not a function – Christian01 Dec 07 '20 at 13:50
  • It would work if you are using node.js. If you want to do this client-side then you need other modules. You can visit this for more information on how to read files on the client-side: https://developer.mozilla.org/en-US/docs/Web/API/FileReader – Megh Agarwal Dec 07 '20 at 14:09
  • How is it possible to include node.js? – Christian01 Dec 07 '20 at 14:25
  • Node.js is actually a different thing to be considered. When talking about client side Javascript, you don't really need Node.js since, Node.js is used for backend purposes. It is basically a JavaScript runtime environment that executes JavaScript code outside a web browser. – Megh Agarwal Dec 07 '20 at 17:57
0

First thing is you cannot access files in local directory using javascript. Secondly, you can access files hosted in any server including your localhost(via web URL). I assume you are hosting your app in IIS or nodeJs, then below code will work. Note URL here is relative to your app's root directory.

// Alias url: http://localhost:4200/post.json
    $.getJSON( "posts.json", function( json ) {
      console.log( "JSON Data: " + json);
      console.log( "particular data Data: " + json.post0 );
     });

You can modify in memory data like below and use it anywhere


    $.getJSON( "posts.json", function( json ) {
     console.log( "JSON Data: " + json);
     json.post0 = 'Another value' );
    });

But this will not update your file. You can make another ajax call to serverside, your server side technology (.net, java or NodeJs) will update the file.

note: Here I used jquery. You can use appropriate technology.

Shridhar Gowda
  • 59
  • 2
  • 10
-1

Due to local filerestriction to script languages, how I know it is just possible to load files from a server. You could set up fast in your local folder a webserver e.q.:

npm i http-server

Then execute it with:

npm http-server .

It will open a localhost:8080 where your index file is displayed. Then you are able to load your json file via XMLHttpRequest or via import in the top of your JS file. To edit the loaded file you could parse it:

JSON.parse(file-content);
lortschi
  • 2,768
  • 2
  • 18
  • 12
-1

I also tried to read few JSON files on a local relative path. This can be made without using jQuery, or any server coding. Some people assign a data string variable inside the JSON file. And this JSON data can be referenced as a js script in a page.

<script type="text/javascript" src="./path/to/myfile.json"></script> 

This is not indeed the structure of an usual JSON file. And actually, this is working more like a JavaScript file. It's been said, that JSON files are also JavaScript files. For more properties, it's difficult to write in the same line. And you'd like to split the data string into more text lines:

data = '[' + 
  '\n{"name" : "Independence Day", "id" : "ID"}' + 
  ',\n{"name" : "Stars Wars", "id" : "SW"}' + 
  ',\n{"name" : "Star Treck", "id" : "ST"}' + 
']'; 

But this file can be written more like an usual JSON file. And you won't have to deal with the string concatenation:

data = [
  {
    "name": "Independence Day", "id": "ID"
  }, 
  {
    "name": "Stars Wars", "id": "SW"
  },
  {
    "name": "Star Treck", "id": "ST"
  }
] 

The file can be edited in any text editor, that accepts standard text. Can be either Notepad, Wordpad, that could be found on any operating system.

Or you can use the Microsoft Visual Source Code, or just Code. But for this should be used a plugin for interpreting "TypeScript". By default the Code editor knows how to encode the .JSON files. And it has a very advanced interface for analyzing the file errors. This application has many free plugins especially that for Java.

Additionally, you can add a new expression before parse. In the .js script file write first a stringify instruction:

function load() {
    var str = JSON.stringify(data); 
    var mydata = JSON.parse(str); 

    const n = mydata.length; 
    for (let i = 0; i < n; i++) { 
        alert(mydata[i].name);
        alert(mydata[i].id);
    }
} 

This will not work if there are more scripts in a main page. It is better to move the load function into the main page. Then in another main() function, the load could be called. Otherwise the function won't be visible from another script. (Supposing the onload function it is main(), not load()). The onload attribute can be placed in the html body tag:

<body onload="main()">

Then you'll have to declare the main() loading function:

<script type="text/javascript">
function main(){
load(); 
}
</script>

Or you can include your own Script.js file as a src attribute, if load is the only function, that loads at startup. However, this may be tested, depending of the existing conditions and requirements.

That list with movies was just an example of how to read the file. In practice, you may want to read a list of drafters, or customers. Using JavaScript and HTML, you don't need very expensive programs. And that list with sensitive information, it is not placed on server, or a public location.

The real reason of using the JSON properties and methods, was that reading a local file (regardless of its own type) becomes possible. Because from security reasons, just simple JavaScript cannot access the content of local files from a WEB page.

Of course, unless the user will not use the input "file" control, or some drag and drop features, but sometimes, the user doesn't want to pick a file by hand, and it would be useful to do this from a script, or another application.

Anything written here, it is based on searching similar questions on older stack-overflow answers and google. And certainly I had checked myself, if it's working like this. But I must admit, I have an older operating system, I'm still working with some older browsers, and my skills in the programming field are not so advanced.

Best regards, Adrian Brinas. Hopefully it will help a lot.

Adrian
  • 60
  • 2
  • "It's been said, that JSON files are also JavaScript files. — They are not. That is why you have to change the "structure" for that to work. You're writing JavaScript instead of JSON. – Quentin Aug 08 '22 at 06:58
  • "Additionally, you can add a new expression before parse. In the .js script file write first a stringify instruction" — Converting a JS data structure to JSON and then immediately converting it back is **occasionally** useful as a form of deep cloning for simple data structures but entirely pointless here. – Quentin Aug 08 '22 at 06:59
  • "The onload attribute can be placed in the html body tag:" — Now it is 2011 (oh, wait, that was over a decade ago) and we don't need to support IE 8, we can use `addEventListener` without pollyfills and there's no reason to resort to `on*` attributes. For that matter, there's no need to wait for the `load` event since we can use `DOMContentLoaded`. For that matter we can just `defer` the script. For that matter we can just not do anything to delay the script because it isn't interacting with the DOM in the first place. – Quentin Aug 08 '22 at 07:02
  • "Another closer look, you can use a JSONP file instead that JSON." — JSONP is a dirty and dangerous hack for loading data across origins. If you're loading hardcoded data from your own site, then it is pointless. If you are loading data across origins then we have CORS now. The standard structure of a URL for JSONP is not `myfile.jsonp` it is `myfile.js?callback=nameOfFunctionToDynamicallyCall`. – Quentin Aug 08 '22 at 07:04
  • You haven't covered the part about **editing** the file. – Quentin Aug 08 '22 at 07:05
  • Thank you. I had changed – Adrian Aug 08 '22 at 13:34