Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

300
Views
How to convert a list that is a string into a list in Javascript?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!