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)
Answer from clucle on Stack Overflowvar 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
});
}
How about storing the alerts as records in an array instead of properties of a single object ?
var alerts = [
{num : 1, app:'helloworld',message:'message'},
{num : 2, app:'helloagain',message:'another message'}
]
And then to add one, just use push:
alerts.push({num : 3, app:'helloagain_again',message:'yet another message'});
You can do this with Object.assign(). Sometimes you need an array, but when working with functions that expect a single JSON object -- such as an OData call -- I've found this method simpler than creating an array only to unpack it.
var alerts = {
1: {app:'helloworld',message:'message'},
2: {app:'helloagain',message:'another message'}
}
alerts = Object.assign({3: {app:'helloagain_again',message:'yet another message'}}, alerts)
//Result:
console.log(alerts)
{
1: {app:'helloworld',message:'message'},
2: {app:'helloagain',message:'another message'}
3: {app: "helloagain_again",message: "yet another message"}
}
EDIT: To address the comment regarding getting the next key, you can get an array of the keys with the Object.keys() function -- see Vadi's answer for an example of incrementing the key. Similarly, you can get all the values with Object.values() and key-values pairs with Object.entries().
var alerts = {
1: {app:'helloworld',message:'message'},
2: {app:'helloagain',message:'another message'}
}
console.log(Object.keys(alerts))
// Output
Array [ "1", "2" ]
appending to json file in javascript - Stack Overflow
Appending to JSON object using JavaScript - Stack Overflow
How to add data to a JSON file in JavaScript?
How do I append to an array inside a json file in node?
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 ....
});
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!
I'm using the Webix framework and I'm trying to save information from a datatable to my server. To do that I'm trying to send all of the information in one big JSON string, but I don't know how to append it to a single variable.
var grabSelected = grida.getSelectedId(true);
var record = {};
$.each(grabSelected, function(index, value) {
record = grida.getItem(value);
});It just returns the last item selected, but I'm trying to get all of them. What am I missing?
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 ?
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.
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!');
});
})