简体   繁体   中英

How can i convert CSV file to JSON format in React?

Do i have to make a variable and paste the CSV data and then convert to JSON or please specify some methods. Thank You!

I'm not familiar enough with react to know if there is a necessity to make it react specific, but if you are open to using a library, this one is superb:

https://github.com/okfn/csv.js/

This library allows you to

  1. Fetch the CSV from a url
  2. Parse that CSV into an array
  3. Serialize it back into CSV format if needed

So for you, I would say, use this library to fetch the data, parse the data, and then just JSON.stringify the array.

If you don't need to do it programmatically, why not just take the CSV, and put array brackets around it, and set your variable as that?

For example, my CSV:

Apple,Banana,Strawberry,
Pickle,Cucumber,Lettuce,
Milke,Bread,Onions,

Then I turn it into an array:

[['Apple','Banana','Strawberry'],
['Pickle','Cucumber','Lettuce'],
['Milk','Bread','Onions']]

You can just use built in Excel functions like concatenate to turn it into this format if your CSV file is really big and this is just a one-off exercise

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM