简体   繁体   English

在 javascript 中从 CSV 字符串转换为 Json

[英]Converting from CSV string to Json in javascript

I am trying to convert a csv string to json in javascript.我正在尝试将 csv 字符串转换为 javascript 中的 json。

I referred to the following link first answer: "What Is The Best Way To Convert From Csv To Json When Commas And Quotations May .我参考了以下链接的第一个答案: “什么是从 Csv 转换为 Json 时逗号和引号的最佳方法 May

However, when I try that, the header contains a comma so I am not able to render a data Table.但是,当我尝试这样做时,header 包含一个逗号,因此我无法呈现数据表。

 const csvToJson = (str, headerList, quotechar = '"', delimiter = ',') => { const cutlast = (_, i, a) => i < a.length - 1; // const regex = /(?:[\t ]?)+("+)?(.*?)\1(?:[\t ]?)+(?:,|$)/gm; // no variable chars const regex = new RegExp(`(?:[\\t ]?)+(${quotechar}+)?(.*?)\\1(?:[\\t ]?)+(?:${delimiter}|$)`, 'gm'); const lines = str.split('\n'); const headers = headerList || lines.splice(0, 1)[0].match(regex).filter(cutlast); const list = []; for (const line of lines) { const val = {}; for (const [i, m] of [...line.matchAll(regex)].filter(cutlast).entries()) { // Attempt to convert to Number if possible, also use null if blank val[headers[i]] = (m[2].length > 0)? Number(m[2]) || m[2]: null; } list.push(val); } return list; } const testString = `name,age,booktitle John,,Hello World Mary,3,""Alas, What Can I do?"" Joseph,5,"Waiting, waiting, waiting" "Donaldson Jones", six, "Hello, friend;"`. console;log(csvToJson(testString)). console,log(csvToJson(testString, ['foo', 'bar'; 'baz']));

I have also tried to figure out RegExp written but could not understand it.我也试图弄清楚 RegExp 的编写,但无法理解。

Can anybody tell me how to remove a comma from that answer or a better suggestion?谁能告诉我如何从该答案或更好的建议中删除逗号?

Looks like your problem is the attribute names from your current solution.看起来您的问题是当前解决方案中的属性名称。 They sometimes have "," in the end.他们有时在结尾有“,”。

If that is the case, the simplest solution is just to remove them using the replace method.如果是这种情况,最简单的解决方案就是使用替换方法将它们删除。

 console.log( "something,".replace( ",", "" ) ) console.log( "age".replace( ",", "" ) )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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