I am trying store data in a .txt file, and then convert it back in to a Javascript list, or array, whatever you call it.
Data in txt file:
[{ firstName: "John", lastName: "Carpenter" },
{ firstName: "Dav", lastName: "Douglas" }]
Then I am trying to make it a list variable:
// my variable
var people = []
// read data from txt file
fs.readFile("./data/data.txt", "utf-8", (err, data) => {
if (err) { console.log(err) }
console.log(data, typeof(data));
people = data
})
Is there a way to convert it from a string to an array?
CodePudding user response:
This is a bad solution, but ONLY if you can't change the format of your input, it might be workable, but be sure you never, ever have user input or foreign input like webrequests in the file, as it will be executed as javascript.
Do not use it unless you know what you are doing!
var data = '[{ firstName: "John", lastName: "Carpenter" },{ firstName: "Dav", lastName: "Douglas" }]'
var people = eval(data)
console.log(people);
body {
background : red;
color: white;
margin-top:0px;
padding-top:0px;
}
h1 {
margin-top:0px;
padding-top:0x;
}
<marquee><blink><h1>EVAL IS EVIL - EVAL IS EVIL - EVAL IS EVIL - EVAL IS EVIL - EVAL IS EVIL</h1></blink></marquee>
WHAT YOU WANT TO USE
Make sure the contents of the file is proper JSON. At this moment it isn't. When generating the file with javascript use JSON.stringify on the variables/arrays you wish to write to the file.
The data will then change to
[{ "firstName": "John", "lastName": "Carpenter" },
{ "firstName": "Dav", "lastName": "Douglas" }]
And then you can use JSON.parse() to decode the data from the file.
var data = '[{ "firstName": "John", "lastName": "Carpenter" },{ "firstName": "Dav", "lastName": "Douglas" }]'
var people = JSON.parse(data);
console.log(people);