[英]Convert JSON to CSV format using Javascript
I'm trying to convert this Javacript Object into a CSV file without any frameworks just in vanilla JS我正在尝试将这个 Javacript Object 转换为没有任何框架的 CSV 文件,只是在 vanilla JS 中
Following are my json:以下是我的 json:
[{
customer_details: {
firstName: "SEBO",
lastName: "RAQUI",
address1: "1990 empty road",
address2: "",
address3: "",
zipcode: "99199",
country: "US",
},
order_details: {
items: [
{
listPrice: 14,
productID: "IEBPTDIEBAIEB119SJM",
quantity: 11,
description: "RED SHOES",
},
{
listPrice: 9,
productID: "PTDIIEB2886JG10",
quantity: 8,
description: "WHITE SHIRT",
},
],
},
payment: "AMEX",
shipping: { type: "Express", HSCode: "ARKA10" },
}]
following is the csv format output以下是 csv 格式 output
customer_details.firstname,customer_details.lastname,customer_details.address1,customer_details.address2,customer_details.address3,customer_details.zipcode,customer_details.country,order_details.items.listPrice,order_details.items.productID,order_details.items.quantity,order_details.items.description,payment,shipping.type,shipping.HSCode
SEBO,RAQUI,1990 empty road,,,99199,US,14,EBPTDIEBAIEB119SJM,11,RED SHOES,AMEX,Express,ARKA10
,,,,,,,9,PTDIIEB2886JG10,8,WHITE SHIRT,,,
Try this:尝试这个:
const JSONtoCSV = (arr, columns, delimiter = ';') =>
[
columns.join(delimiter),
...arr.map(obj =>
columns.reduce(
(acc, key) => `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`,
''
)
)
].join('\n');
I modified the delimited to use semicolons like your example showed.我修改了分隔符以使用分号,如您的示例所示。
Resource: https://github.com/30-seconds/30-seconds-of-code/blob/master/snippets/JSONtoCSV.md资源: https://github.com/30-seconds/30-seconds-of-code/blob/master/snippets/JSONtoCSV.md
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.