thejsdevelopers
thejsdevelopers

Reputation: 27

How can I convert txt files with this type of data to json?

So I'm just trying to use some data that I got in JavaScript but its not in a suitable format. It's .txt file and it's not really formatted well.

I've tried to find out what format the data in the .txt file was but I couldn't.

Here's an example of what the .txt file contains:

age, name, height_cm
20, John, 176
35, Robert, 185
28, Julia, 162

Of course the .txt file is different and contains hundreds of lines.

So I need some guidance in finding a way to convert this data to json if possible.

Upvotes: 0

Views: 53

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30705

I would suggest using a dedicated CSV parser that is specifically designed for this type of problem, it will handle quoted fields and all other kind of gotchas for you.

I would definitely avoid rolling your own.. these libraries are RFC 4180 compliant.

jquery-csv is one, Papa Parse is another that are worth trying.

With jquery-csv it's pretty simple to parse text to objects:

const csv = 
`age,name,height_cm
20,John,176
35,Robert,185
28,Julia,162`;

const options = { separator: "," };

console.log("CSV input:", `\n${csv}\n\n`);
console.log("Parsed output:", $.csv.toObjects(csv, options));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/1.0.5/jquery.csv.min.js"></script>

Upvotes: 1

Related Questions