How to write and read an array of objects to a file - javascript

I have this array of objects:
var people = {name:'list 1',mode:0,friends:[{user:1,code:'red'},{user:2,code:'blue'}]};
I want to write it to a file so if the node server crashes I dont lose the data. I did this:
//define variables from file
var file = "../../people.txt";
var open = fs.readFileSync(file);
va data = open.toString();
var name = data.name;
var mode = data.mode;
var friends = data.friends;
whenever a variable changes I save it to a file like this:
function update() {
//dosomething
name = 'new list';
mode = 1;
friends = [{user:4,code:'red'},{user:6,code:'blue'}]
fs.writeFileSync(file,`{name:'${name}',mode:${mode},friends:${friends}'}`,{encoding:'utf8',flag:'w'});
}
This is output onto the file
{name:'list 1',mode:0,friends:[object, object]}
and the data cant be read at all. What am I supposed to do here?
Thank you.

You should convert the JSON data into a string format using JSON.stringify() before writing it to a file, and when reading them out, you should parse the string into JSON using JSON.parse()
More details are here and how to read/write JSON files

Related

How to add a new string to an array in a json file

I am making a discord bot and I have a profile.json file and I want to be able to make it so when you do a certain command, it adds the argument you input to the array. like so
{"Profile_name":"id":"idhere", "array":["item_1"]}
I want to be able to add more items to that array when a user uses the command to do so
First, u have syntax error in your json.
Second, u ask for ready code.
Third, here, u have scrap that you can start with:
const fs = require("fs");
// read file
let my_json = fs.readFileSync(path_to_file);
my_json = JSON.parse(my_json);
// edit variable here
// for example
my_json.array.push("new item");
// write file
my_json = JSON.stringify(my_json);
fs.writeFileSync(path_to_file, my_json);
You need to read the file, push new element to array and then save the file
const fs = require('fs');
//reads the file
let rawdata = fs.readFileSync('file.json');
//convert to JSON object
let json = JSON.parse(rawdata);
//Before: {"Profile_name":"name","id":"idhere", "array":["item_1"]}
json["array"].push("more");
//After: {"Profile_name":"name","id":"idhere", "array":["item_1","more"]}
//Convert to string
let data = JSON.stringify(json);
//Save the file
fs.writeFileSync('file.json', data);

Turning JSON.parse() return type to an array of object

I have defined a file called note-data.json which contains json data. In the following code a variable of type of array called notes is declared. What I want to achieve is that the program read the json file save it in the noteString variable and then make a array of object with JSON.parse() from noteString and put it into notes array. So I can add new objects to the json file. But when the programme gets to the line note.push() it complains since, I think, the type of notes has turned to a string and push is not define for string. How can I get around this issue?
Please ignore the fact that if the json file is not provided the the program crashes.
My code:
const addNote = (title, body) => {
let notes= [];
const note = {
title,
body
};
const notesString = fs.readFileSync('node-data.json', 'utf8');
notes = JSON.parse(notesString);
notes.push(note);
fs.writeFileSync('node-data.json', JSON.stringify(note));
}
File note-data.json:
{"title":"Greeting","body":"Hello"}
I think you are fumbling with your variables here. From what I understood - you want to read JSON from a file and append that JSON to an array, right? Following code will help you do just that
const addNote = (title, body) => {
let notes= []; //Declare an array
const note = JSON.parse(fs.readFileSync('node-data.json', 'utf8')); //read and parse file contents
notes.push(note); //Append new JSON to your array
//This line below appears to have no purpose ??
fs.writeFileSync('node-data.json', JSON.stringify(note));
}

How to store and get data from a json file with javascript?

I would like to create a little kind of CMS. For that I want to code a function, which automatically creates a list of the files, which were created with the CMS. This list sould be display in a html file and styled with CSS. For that I want to create a json-File, in which i store the title and the location of the new file.
Then it should look like this:
{
"new_sites":
{
"title": "source",
"otherTitle": "otherSource"
}
}
Now I want to know, how I can get (or store new) data from the json-File and use it as variables in javascript so that I can display it on the html page.
Given these three variables:
var myNewSite = 'newSite';
var myNewTitle = 'newTitle';
var myNewSource = 'newSource';
and your final json variable initialized in this way:
var myJson = {};
You could simply:
myJson[myNewSite] = {
myNewTitle: myNewSource
};
You can use Jquery api to get data from json-file.Suppose you have a data.json file in directory.
<script>
var container={};
$.getJSON('data.json', function(data) {
container=data;
});
</script>

Parsing a JSON object with Javascript, just won't work

I'm using this code to get a JSON file stored in the same folder.
var schedtotal = 0;
var requestURL11 = 'schedtotal.json';
var request11 = new XMLHttpRequest();
request11.open('GET', requestURL11);
request11.responseType = 'json';
request11.send();
request11.onload = function() {
window.superHeroes11 = request11.response;
populateHeader11(superHeroes11);
}
function populateHeader11(jsonObj) {
window.schedtotal = jsonObj.total;
console.log("populateHeader function has activated");
console.log(jsonObj);
}
The file looks like this:
{"total": 3}
It's valid JSON. I'm trying to extract the value of total using the same exact method that I've used successfully for all the other JSON parsings in the rest of the file (which I have not included here).
When populateHeader11 is called, it doesn't change schedtotal to equal total. It remains at its original setting of 0. The console log returns from the function as having activated and also returns the JSON file so I know it can access it at least.
I've tried changing .jsonObj.total to .jsonObj['total'] and it didn't change anything.
Previous times I've screwed around with this, it has sometimes returned an error saying it can't get 'total' from null. Now it just doesn't return anything in its current state. What is going on?
You need to parse the JSON string into an object before you try and access the total field.
var jsonString = "{\"total\": 3}";
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj.total);

Source an object from a text file in javascript?

How do you source the data of multiple objects from a text file in JavaScript? I'm creating a program that will work with employee data and each employee will be treated as an object; I want the object data to come from an external source (i.e. a text file or an Excel spreadsheet), instead of having to explicitly write out the data for each employee within the code of the program. The multiple employee objects will be pushed into an array and then I'll interact with them in various ways. In the code below, I've had to explicitly write out employee data (see below). I want to source that data from some external source instead. Thanks!
function Employee (name, roomID, email)
{
this.name = name;
this.roomID = roomID;
this.email = email;
}
function EList()
{
this.employees = [];
this.firstindex = 0;
}
var employeeList = new EList();
var employee1 = new Employee("Aman Mundra", "D3-1", "aman.s.mundra#gmail.com"); //parameters inside parenthesis
var employee2 = new Employee("John Doe", "D4-1", "john.doe#gmail.com");
var employee3 = new Employee("Jane Doe", "D4-2", "jane.doe#gmail.com");
employeeList.employees.push(employee1, employee2, employee3)
What you are talking about is JSON. Make sure you are using JSON and the functions are already written for you. See json.com and json.org.
Particularly you would use JSON.parse to parse your text file, which would come in the form of a string after you have ajaxed your file in.
Here is the documentation for JSON.parse.
You might be looking for something along these lines if you can work with a CSV file: Javascript loading CSV file into an array
Why JavaScript? What are the other moving parts?

Categories

Resources