Skip to content

Instantly share code, notes, and snippets.

@cocoalix
Last active August 10, 2022 23:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cocoalix/23281d5f2037bb99394b3c51053a6e24 to your computer and use it in GitHub Desktop.
Save cocoalix/23281d5f2037bb99394b3c51053a6e24 to your computer and use it in GitHub Desktop.
なんか\r\nを\nで分割することの危険性をいい感じに証明するやつ
/**
* CSVからJsonを作成する
* @param {String} csv
* @return {Json}
*/
const generateCsvToJson = (csv) =>
{
const csvLineList = csv.split('\n');
const columnNameList = [];
const resultArray = [];
for (const [index, line] of csvLineList.entries()) {
if (!line || !line.trim()) {
continue;
}
const columnList = line.split(',');
if (index === 0) {
for (const column of columnList) {
columnNameList.push(column);
}
continue;
}
const node = {};
for (const [columnIndex, column] of columnList.entries()) {
node[columnNameList[columnIndex]] = column;
}
resultArray.push(node);
}
return resultArray;
}
const x = "receive_date,shipped_date,pref_code,shipping_code\r\n2022-08-01 11:00:00,2022-08-02 16:35:00,1,e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\r\n2022-08-03 15:00:00,2022-08-04 18:29:00,2,60303ae22b998861bce3b28f33eec1be758a213c86c93c076dbe9f558c11c752\r\n";
const json = generateCsvToJson(x);
console.log(json);
console.log(json[0]['shipping_code']);
/*
実行結果:
cocoalix@Aki:~/winhome/Documents$ node -v
v16.13.1
cocoalix@Aki:~/winhome/Documents$ node csvToJson.js
[
{
receive_date: '2022-08-01 11:00:00',
shipped_date: '2022-08-02 16:35:00',
pref_code: '1',
'shipping_code\r': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\r'
},
{
receive_date: '2022-08-03 15:00:00',
shipped_date: '2022-08-04 18:29:00',
pref_code: '2',
'shipping_code\r': '60303ae22b998861bce3b28f33eec1be758a213c86c93c076dbe9f558c11c752\r'
}
]
undefined
cocoalix@Aki:~/winhome/Documents$
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment