'Modifying json file via Javascript
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 class="name" placeholder="name">
<input class="email" placeholder="email">
<button class="submit">Add User</button>
</body>
</html>
JSON:
[
{
"id": 1,
"name": "Leanne Gr",
"email": "[email protected]"
}
]
Solution 1:[1]
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')
}
})
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yalcin Kilic |
| Solution 2 | Philo |
