Home > Software design >  Modifying json file via Javascript
Modifying json file via Javascript

Time:04-22

I am new to Javascript and have already programmed a system where I can search up and filter the users in my data.json file. But how can I build an application that can add users to the data.json file. Thank you for your help, Benjamin

HTML:

<html lang="en">
    <head>
        <link rel="Stylesheet" href="style.css">
        <script src="main.js"></script>
    </head>
    <body>
        <input  placeholder="name">
        <input  placeholder="email">
        <button >Add User</button>
    </body>
</html>

JSON:

[
  {
      "id": 1,
      "name": "Leanne Gr",
      "email": "[email protected]"
  }
]

CodePudding user response:

You can use the npm package

browserify-fs

to do that. When you installed the package you can use the fileSystem.writeFile() function:

const fileSystem = require("browserify-fs")

const client = {
 "Name": "John Doe",
 "Mail": "[email protected]"
}
const data = JSON.stringify(client)

fileSystem.writeFile("./data.json", data, err=>{
 if(err){
   console.log("Error writing file" ,err)
 } else {
   console.log('JSON data is written to the file successfully')
 }
})

CodePudding user response:

You Can do this with XMLHttpRequest requests. But you need a server to host your json.

You can host a local server using json-server npm package to host your own JSON server

In conclusion you need a server and XMLHttpRequest to edit using Javascript

Other wise you need a Server Side program language like PHP

Note that Javascript Client Side programming Language

  • Related