This answer is assuming that you are working under Node.js.
As I understand your problem you need to solve a few different programming questions.
read and write a .json file
const fs = require("fs"); let usersjson = fs.readFileSync("users.json","utf-8");transform a json string into a javascript array
let users = JSON.parse(usersjson);append an object to an array
users.push(obj);transform back the array into a json string
usersjson = JSON.stringify(users);save the json file
fs.writeFileSync("users.json",usersjson,"utf-8");
This answer is assuming that you are working under Node.js.
As I understand your problem you need to solve a few different programming questions.
read and write a .json file
const fs = require("fs"); let usersjson = fs.readFileSync("users.json","utf-8");transform a json string into a javascript array
let users = JSON.parse(usersjson);append an object to an array
users.push(obj);transform back the array into a json string
usersjson = JSON.stringify(users);save the json file
fs.writeFileSync("users.json",usersjson,"utf-8");
If your code is running in the browser and users.json is an output file, I guess you already have access to its content.
Use the push() method.
Also, note the missing commas in your objects.
var obj = {
username: "James",
surname: "Brandon",
id: "[2]"
};
var users = [
{
"username": "Andy",
"surname": "Thompson",
"id": [0]
},
{
"username": "Moe",
"surname": "Brown",
"id": [1]
}
];
users.push(obj);
console.log( JSON.stringify(users) );
Now that you have the updated array of objects you can upload it to the server (check this question) or offer a download to the user (check this other question).
As you have been already told, there is no way to directly update client-side a file in the server. It is also not possible to save it directly into the client filesystem.
Append a JSON file correclty
How to add data to a JSON file in JavaScript?
javascript - Write / add data in JSON file using Node.js - Stack Overflow
Append an object to an existing JSON file
Videos
var data = JSON.parse(txt); //parse the JSON
data.employees.push({ //add the employee
firstName:"Mike",
lastName:"Rut",
time:"10:00 am",
email:"[email protected]",
phone:"800-888-8888",
image:"images/mike.jpg"
});
txt = JSON.stringify(data); //reserialize to JSON
JSON stands for Javascript object notation so this could simply be a javascript object
var obj = {employees:[
{
firstname:"jerry"
... and so on ...
}
]};
When you want to add an object you can simply do:
object.employees.push({
firstname: "Mike",
lastName: "rut"
... and so on ....
});
Hello.
I try to write on a JSON file, but this is what I got :
https://hastebin.com/lilomarede.json
As you can see, the id5 is complelty out of the JSON file.
I tried to use bizarre stuff like this (my actual code):
https://hastebin.com/olehohomoy.js
var punJson = "," + (punJson[punId] = { message: punMessage });wich punID and punMessage are both values I get just before this little piece of code.
I tried to do
var punJson = "," + (punJson[punId] = { message: punJson[punMessage] });Obviously, this dosen't work.
I got the error
TypeError : Cannot set property 'id5' of undefined
Any ideas ?
If this JSON file won't become too big over time, you should try:
Create a JavaScript object with the table array in it
var obj = { table: [] };Add some data to it, for example:
obj.table.push({id: 1, square:2});Convert it from an object to a string with
JSON.stringifyvar json = JSON.stringify(obj);Use fs to write the file to disk
var fs = require('fs'); fs.writeFile('myjsonfile.json', json, 'utf8', callback);If you want to append it, read the JSON file and convert it back to an object
fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){ if (err){ console.log(err); } else { obj = JSON.parse(data); //now it an object obj.table.push({id: 2, square:3}); //add some data json = JSON.stringify(obj); //convert it back to json fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back }});
This will work for data that is up to 100 MB effectively. Over this limit, you should use a database engine.
UPDATE:
Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback). With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.
Please try the following program. You might be expecting this output.
var fs = require('fs');
var data = {}
data.table = []
for (i=0; i <26 ; i++){
var obj = {
id: i,
square: i * i
}
data.table.push(obj)
}
fs.writeFile ("input.json", JSON.stringify(data), function(err) {
if (err) throw err;
console.log('complete');
}
);
Save this program in a javascript file, say, square.js.
Then run the program from command prompt using the command node square.js
What it does is, simply overwriting the existing file with new set of data, every time you execute the command.
Happy Coding.
if you are using jQuery's getJSON or parseJSON(), you have a javascript object you can manipulate. for example:
$.getJSON( "/test.json", function( data ) {
// now data is JSON converted to an object / array for you to use.
alert( data[1].cast ) // Tim Robbins, Morgan Freeman, Bob Gunton
var newMovie = {cast:'Jack Nicholson', director:...} // a new movie object
// add a new movie to the set
data.push(newMovie);
});
All you have to do now is save the file. You can use jQuery.post() to send the file back to the server to save it for you.
Update: Posting an example
//inside getJSON()
var newData = JSON.stringify(data);
jQuery.post('http://example.com/saveJson.php', {
newData: newData
}, function(response){
// response could contain the url of the newly saved file
})
On your server, example using PHP
$updatedData = $_POST['newData'];
// please validate the data you are expecting for security
file_put_contents('path/to/thefile.json', $updatedData);
//return the url to the saved file
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js" ></script>
</head>
<body>
<?php
$str = file_get_contents('data.json');//get contents of your json file and store it in a string
$arr = json_decode($str, true);//decode it
$arrne['name'] = "sadaadad";
$arrne['password'] = "sadaadad";
$arrne['nickname'] = "sadaadad";
array_push( $arr['employees'], $arrne);//push contents to ur decoded array i.e $arr
$str = json_encode($arr);
//now send evrything to ur data.json file using folowing code
if (json_decode($str) != null)
{
$file = fopen('data.json','w');
fwrite($file, $str);
fclose($file);
}
else
{
// invalid JSON, handle the error
}
?>
<form method=>
</body>
data.json
{
"employees":[
{
"email":"11BD1A05G9",
"password":"INTRODUCTION TO ANALYTICS",
"nickname":4
},
{
"email":"Betty",
"password":"Layers",
"nickname":4
},
{
"email":"Carl",
"password":"Louis",
"nickname":4
},
{
"name":"sadaadad",
"password":"sadaadad",
"nickname":"sadaadad"
},
{
"name":"sadaadad",
"password":"sadaadad",
"nickname":"sadaadad"
},
{
"name":"sadaadad",
"password":"sadaadad",
"nickname":"sadaadad"
}
]
}
If you want the file to be valid JSON, you have to open your file, parse the JSON, append your new result to the array, transform it back into a string and save it again.
var fs = require('fs')
var currentSearchResult = 'example'
fs.readFile('results.json', function (err, data) {
var json = JSON.parse(data)
json.push('search result: ' + currentSearchResult)
fs.writeFile("results.json", JSON.stringify(json))
})
In general, If you want to append to file you should use:
fs.appendFile("results.json", json , function (err) {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
Append file creates file if does not exist.
But ,if you want to append JSON data first you read the data and after that you could overwrite that data.
fs.readFile('results.json', function (err, data) {
var json = JSON.parse(data);
json.push('search result: ' + currentSearchResult);
fs.writeFile("results.json", JSON.stringify(json), function(err){
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
})
Try this. Don't forget to define anchors array.
var data = fs.readFileSync('testOutput.json');
var json = JSON.parse(data);
json.push(...anchors);
fs.writeFile("testOutput.json", JSON.stringify(json))
I created two small functions to handle the data to append.
- the first function will: read data and convert JSON-string to JSON-array
- then we add the new data to the JSON-array
- we convert JSON-array to JSON-string and write it to the file
example: you want to add data { "title":" 2.0 Wireless " } to file my_data.json on the same folder root. just call append_data (file_path , data ) ,
it will append data in the JSON file, if the file existed . or it will create the file and add the data to it.
data = { "title":" 2.0 Wireless " }
file_path = './my_data.json'
append_data (file_path , data )
the full code is here :
const fs = require('fs');
data = { "title":" 2.0 Wireless " }
file_path = './my_data.json'
append_data (file_path , data )
async function append_data (filename , data ) {
if (fs.existsSync(filename)) {
read_data = await readFile(filename)
if (read_data == false) {
console.log('not able to read file')
}
else {
read_data.push(data)
dataWrittenStatus = await writeFile(filename, read_data)
if dataWrittenStatus == true {
console.log('data added successfully')
}
else{
console.log('data adding failed')
}
}
else{
dataWrittenStatus = await writeFile(filename, [data])
if dataWrittenStatus == true {
console.log('data added successfully')
}
else{
console.log('data adding failed')
}
}
}
async function readFile (filePath) {
try {
const data = await fs.promises.readFile(filePath, 'utf8')
return JSON.parse(data)
}
catch(err) {
return false;
}
}
async function writeFile (filename ,writedata) {
try {
await fs.promises.writeFile(filename, JSON.stringify(writedata,null, 4), 'utf8');
return true
}
catch(err) {
return false
}
}
var data = []
function Client(date, contact) {
this.date = date
this.contact = contact
}
clients = new Array();
for (i = 0; i < 4; i++) {
clients.push(new Client("2018-08-0" + i, i))
}
for (i = 0; i < clients.length; i++) {
var dict = {}
dict['Date'] = clients[i].date
dict['Contact'] = clients[i].contact
data[i] = dict
}
console.log(data)
It's a simple push object to array operation. Please try below
var data=[];
var i;
for (i = 0; i < clients.length; i++) {
data.push({
date:clients.date,
contact:clients.contact
});
}