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.
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 ?
How to add data to a JSON file in JavaScript?
Append an object to an existing JSON file
javascript - How do I add to an existing json file in node.js - Stack Overflow
javascript - Write / add data in JSON file using Node.js - Stack Overflow
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 ....
});
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!');
});
})
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.
I’m working on a chat client and server to learn about API’s and now I need to write the messages submitted by users into the master chat log (a json file with a messages array inside of it). I have been searching for different approaches and they all error out somehow. I’m using node and express for routing if that helps.
tldr; how should one append an object to an array inside a json file using node.
edit: I’ve taken carcigenocate’s advice. I open the file, make the changes in memory, then write to the file and reload it to reflect changes. I am still open to improvements on this design!
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"
}
]
}