Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

302
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda