Is it possible to generate a JSON file with Javascript?

Asked

Viewed 1,113 times

-2

I had done a PHP project that dealt with JSON data, where I could create new files with data or overwrite existing ones. Now I want to redo the project using Javascript, however I did not find any way to generate/create/overwrite a JSON file. I just learned how to open a JSON file and store its contents in a variable and edit the content. But after the code makes the changes to the data, I want to export them back to the JSON file. Can I do this using JS, AJAX or something? Or just PHP itself?

  • 4

    You want to do this on the client side or using Node.js on the server?

  • 1

    You must use Node.JS and the module fs (file system) for this, since it is not possible to interact with the file system directly by client-side Javascript.

  • @Luizfelipe HTML 5 has an api to write data in the browser store. Even in earlier versions you can write to a blob and serve as a file, or save data to a cookie.

  • 2

    But managing (how to edit) files from a computer does not (like files from your desktop). This would be a little harmful to security. API’s like the localStorage, File, Blob or even Cookies do not represent an ability to interact directly with the FS.

2 answers

0

First, connect executed in browser nay can touch anything outside the browser, for example manage files, all that is available for use is what the browser allows

So if you want to create a system that saves data persistently in JSON files, you should use a server, an option, since you want to use Javascript is Nodejs, which runs JS on the server side, of course with some functionality and more and others less. If you use it you can manage files with the library fs (I will not put examples of use, because it has some different ways of doing the 4 operations - creation, reading, writing and deletion)

There are alternatives if you do not want or may not have a server:

  • Use the storage local (Localstorage, Sessionstorage or Cookie), that is, the change is made only on the machine that made that change.

  • Use a Baas (backend as a service), for example firebase, which has a very simple real-time Nosql database to use, just add the API scripts the tool provides to your HTML and make the changes through them

-1

You can do this by creating an API on Node.js using filesystem with only one require('Fs'), you will only need to install Node on your friend server, hope to have helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.