Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

301
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda