Saya memiliki tautan yang membuka data JSON di browser, tetapi sayangnya saya tidak tahu cara membacanya. Adakah cara untuk mengonversi data ini menggunakan JavaScript dalam format CSV dan menyimpannya dalam file JavaScript?
Datanya terlihat seperti:
{
"count": 2,
"items": [{
"title": "Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)",
"description": "Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China\u2019s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store\u2019s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone",
"link": "http:\/\/wik.io\/info\/US\/309201303",
"timestamp": 1326439500,
"image": null,
"embed": null,
"language": null,
"user": null,
"user_image": null,
"user_link": null,
"user_id": null,
"geo": null,
"source": "wikio",
"favicon": "http:\/\/wikio.com\/favicon.ico",
"type": "blogs",
"domain": "wik.io",
"id": "2388575404943858468"
}, {
"title": "Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)",
"description": "SHANGHAI \u2013 Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone",
"link": "http:\/\/wik.io\/info\/US\/309198933",
"timestamp": 1326439320,
"image": null,
"embed": null,
"language": null,
"user": null,
"user_image": null,
"user_link": null,
"user_id": null,
"geo": null,
"source": "wikio",
"favicon": "http:\/\/wikio.com\/favicon.ico",
"type": "blogs",
"domain": "wik.io",
"id": "16209851193593872066"
}]
}
Yang paling dekat yang bisa saya temukan adalah: Ubah format JSON ke format CSV untuk MS Excel
Tetapi mengunduh dalam file CSV, saya menyimpannya dalam variabel, seluruh data yang dikonversi.
Juga ingin tahu bagaimana mengubah karakter melarikan diri: '\u2019'
kembali normal.
Saya mencoba kode ini:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JSON to CSV</title>
<script src="http://code.jquery.com/jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript">
var json3 = {
"count": 2,
"items": [{
"title": "Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)",
"description": "Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China’s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store’s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone",
"link": "http://wik.io/info/US/309201303",
"timestamp": 1326439500,
"image": null,
"embed": null,
"language": null,
"user": null,
"user_image": null,
"user_link": null,
"user_id": null,
"geo": null,
"source": "wikio",
"favicon": "http://wikio.com/favicon.ico",
"type": "blogs",
"domain": "wik.io",
"id": "2388575404943858468"
},
{
"title": "Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)",
"description": "SHANGHAI – Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone",
"link": "http://wik.io/info/US/309198933",
"timestamp": 1326439320,
"image": null,
"embed": null,
"language": null,
"user": null,
"user_image": null,
"user_link": null,
"user_id": null,
"geo": null,
"source": "wikio",
"favicon": "http://wikio.com/favicon.ico",
"type": "blogs",
"domain": "wik.io",
"id": "16209851193593872066"
}
]
}
//var objJson = JSON.parse(json3.items);
DownloadJSON2CSV(json3.items);
function DownloadJSON2CSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
line += array[i][index] + ',';
}
line.slice(0, line.Length - 1);
str += line + '\r\n';
}
$('div').html(str);
}
</script>
</head>
<body>
<div></div>
</body>
</html>
Tapi sepertinya tidak berhasil. Dapatkah seseorang tolong bantu?
javascript
json
csv
praneybehl.dll
sumber
sumber
2,Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust), ...
?Jawaban:
Cara yang lebih elegan untuk mengonversi json ke csv adalah dengan menggunakan fungsi peta tanpa kerangka kerja apa pun:
var json = json3.items var fields = Object.keys(json[0]) var replacer = function(key, value) { return value === null ? '' : value } var csv = json.map(function(row){ return fields.map(function(fieldName){ return JSON.stringify(row[fieldName], replacer) }).join(',') }) csv.unshift(fields.join(',')) // add header column csv = csv.join('\r\n'); console.log(csv)
Keluaran:
title,description,link,timestamp,image,embed,language,user,user_image,user_link,user_id,geo,source,favicon,type,domain,id "Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)","Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China’s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store’s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone","http://wik.io/info/US/309201303","1326439500","","","","","","","","","wikio","http://wikio.com/favicon.ico","blogs","wik.io","2388575404943858468" "Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)","SHANGHAI – Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone","http://wik.io/info/US/309198933","1326439320","","","","","","","","","wikio","http://wikio.com/favicon.ico","blogs","wik.io","16209851193593872066"
Perbarui ES6 (2016)
Gunakan sintaks yang kurang padat ini dan juga JSON.stringify untuk menambahkan tanda kutip ke string sambil menjaga agar angka tidak dikutip:
const items = json3.items const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here const header = Object.keys(items[0]) let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(',')) csv.unshift(header.join(',')) csv = csv.join('\r\n') console.log(csv)
sumber
null
- sekarang contoh harus menangani null, tidak ditentukan, dan angka dengan benar.\"
yang memungkinkan beberapa bidang untuk "keluar" dari kolom mereka saat dilihat di Excel (yang tampaknya lebih disukai""
sebagai karakter pelarian untuk tanda kutip). Ini dapat diselesaikan dengan menambahkan.replace(/\\"/g, '""')
akhirJSON.stringify(row[fieldName], replacer)
seperti yang saya catat dalam jawaban saya di atas.Ok saya akhirnya mendapatkan kode ini berfungsi:
<html> <head> <title>Demo - Covnert JSON to CSV</title> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script> <script type="text/javascript"> // JSON to CSV Converter function ConvertToCSV(objArray) { var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray; var str = ''; for (var i = 0; i < array.length; i++) { var line = ''; for (var index in array[i]) { if (line != '') line += ',' line += array[i][index]; } str += line + '\r\n'; } return str; } // Example $(document).ready(function () { // Create Object var items = [ { name: "Item 1", color: "Green", size: "X-Large" }, { name: "Item 2", color: "Green", size: "X-Large" }, { name: "Item 3", color: "Green", size: "X-Large" }]; // Convert Object to JSON var jsonObject = JSON.stringify(items); // Display JSON $('#json').text(jsonObject); // Convert JSON to CSV & Display CSV $('#csv').text(ConvertToCSV(jsonObject)); }); </script> </head> <body> <h1> JSON</h1> <pre id="json"></pre> <h1> CSV</h1> <pre id="csv"></pre> </body> </html>
Terima kasih banyak atas semua dukungan untuk semua kontributor.
Praney
sumber
Solusi yang sangat bagus oleh praneybehl, tetapi jika seseorang ingin menyimpan data sebagai
csv
file dan menggunakanblob
metode maka mereka dapat merujuk ini:function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) { //If JSONData is not an object then JSON.parse will parse the JSON string in an Object var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData; var CSV = ''; //This condition will generate the Label/Header if (ShowLabel) { var row = ""; //This loop will extract the label from 1st index of on array for (var index in arrData[0]) { //Now convert each value to string and comma-seprated row += index + ','; } row = row.slice(0, -1); //append Label row with line break CSV += row + '\r\n'; } //1st loop is to extract each row for (var i = 0; i < arrData.length; i++) { var row = ""; //2nd loop will extract each column and convert it in string comma-seprated for (var index in arrData[i]) { row += '"' + arrData[i][index] + '",'; } row.slice(0, row.length - 1); //add a line break after each row CSV += row + '\r\n'; } if (CSV == '') { alert("Invalid data"); return; } //this trick will generate a temp "a" tag var link = document.createElement("a"); link.id="lnkDwnldLnk"; //this part will append the anchor tag and remove it after automatic click document.body.appendChild(link); var csv = CSV; blob = new Blob([csv], { type: 'text/csv' }); var csvUrl = window.webkitURL.createObjectURL(blob); var filename = 'UserExport.csv'; $("#lnkDwnldLnk") .attr({ 'download': filename, 'href': csvUrl }); $('#lnkDwnldLnk')[0].click(); document.body.removeChild(link); }
sumber
var row
dua kali (jika pernyataan dan untuk loop tidak membuat penutupan). Juga loop label / header mungkin dapat dikurangi menjadi satu baris:Object.keys(arrData[0]).join(',')
document.getElementById("lnkDwnldLnk").download = filename;
document.getElementById("lnkDwnldLnk").href = csvUrl;
2. bekerja di IE11:if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, filename);
} else {
document.getElementById('lnkDwnldLnk').click();
}
Saya hanya ingin menambahkan beberapa kode di sini untuk orang-orang di masa mendatang karena saya mencoba mengekspor JSON ke dokumen CSV dan mendownloadnya.
Saya gunakan
$.getJSON
untuk menarik data json dari halaman eksternal, tetapi jika Anda memiliki array dasar, Anda bisa menggunakannya.Ini menggunakan kode Christian Landgren untuk membuat data csv.
$(document).ready(function() { var JSONData = $.getJSON("GetJsonData.php", function(data) { var items = data; const replacer = (key, value) => value === null ? '' : value; // specify how you want to handle null values here const header = Object.keys(items[0]); let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(',')); csv.unshift(header.join(',')); csv = csv.join('\r\n'); //Download the file as CSV var downloadLink = document.createElement("a"); var blob = new Blob(["\ufeff", csv]); var url = URL.createObjectURL(blob); downloadLink.href = url; downloadLink.download = "DataDump.csv"; //Name the file here document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); }); });
Sunting: Perlu dicatat bahwa
JSON.stringify
tanda kutip akan hilang dengan menambahkan\"
. Jika Anda melihat CSV di excel, tidak seperti itu sebagai karakter pelarian.Anda dapat menambahkan
.replace(/\\"/g, '""')
ke akhirJSON.stringify(row[fieldName], replacer)
untuk menampilkan ini dengan benar di excel (ini akan menggantikan\"
dengan""
yang apa yang lebih suka excel).Garis Penuh:
let csv = items.map(row => header.map(fieldName => (JSON.stringify(row[fieldName], replacer).replace(/\\"/g, '""'))).join(','));
sumber
Jika ada yang ingin mendownloadnya juga.
Berikut adalah fungsi kecil yang luar biasa yang akan mengonversi array objek JSON ke csv, lalu mengunduhnya.
downloadCSVFromJson = (filename, arrayOfJson) => { // convert JSON to CSV const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here const header = Object.keys(arrayOfJson[0]) let csv = arrayOfJson.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(',')) csv.unshift(header.join(',')) csv = csv.join('\r\n') // Create link and download var link = document.createElement('a'); link.setAttribute('href', 'data:text/csv;charset=utf-8,%EF%BB%BF' + encodeURIComponent(csv)); link.setAttribute('download', filename); link.style.visibility = 'hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); };
Kemudian sebut seperti ini:
this.downloadCSVFromJson(`myCustomName.csv`, this.state.csvArrayOfJson)
sumber
Cap D'antibes
Ada beberapa opsi yang tersedia untuk menggunakan kembali pustaka canggih yang ada yang berbasis standar.
Jika Anda kebetulan menggunakan D3 dalam proyek Anda, maka Anda dapat langsung memanggil:
d3.csv.format
ataud3.csv.formatRows
berfungsi untuk mengubah array objek menjadi string csv.d3.csv.formatRows
memberi Anda kendali lebih besar atas properti mana yang akan diubah menjadi csv.Silahkan lihat d3.csv.format dan d3.csv.formatRows wiki halaman.
Ada perpustakaan lain yang tersedia juga seperti jquery-csv , PapaParse . Papa Parse tidak memiliki dependensi - bahkan jQuery.
Untuk plugin berbasis jquery, silakan periksa ini .
sumber
Coba Contoh ini
Contoh 1:
JsonArray = [{ "AccountNumber": "123", "AccountName": "abc", "port": "All", "source": "sg-a78c04f8" }, { "Account Number": "123", "Account Name": "abc", "port": 22, "source": "0.0.0.0/0", }] JsonFields = ["Account Number","Account Name","port","source"] function JsonToCSV(){ var csvStr = JsonFields.join(",") + "\n"; JsonArray.forEach(element => { AccountNumber = element.AccountNumber; AccountName = element.AccountName; port = element.port source = element.source csvStr += AccountNumber + ',' + AccountName + ',' + port + ',' + source + "\n"; }) return csvStr; }
Contoh2:
JsonArray = [{ "AccountNumber": "1234", "AccountName": "abc", "inbound": [{ "port": "All", "source": "sg-a78c04f8" }, { "port": 22, "source": "0.0.0.0/0", }] }] JsonFields = ["Account Number", "Account Name", "port", "source"] function JsonToCSV() { var csvStr = JsonFields.join(",") + "\n"; JsonArray.forEach(element => { AccountNumber = element.AccountNumber; AccountName = element.AccountName; element.inbound.forEach(inboundELe => { port = inboundELe.port source = inboundELe.source csvStr += AccountNumber + ',' + AccountName + ',' + port + ',' + source + "\n"; }) }) return csvStr; }
Anda bahkan dapat mengunduh file csv menggunakan kode berikut:
function downloadCSV(csvStr) { var hiddenElement = document.createElement('a'); hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvStr); hiddenElement.target = '_blank'; hiddenElement.download = 'output.csv'; hiddenElement.click(); }
sumber
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>JSON to CSV</title> <script src="http://code.jquery.com/jquery-1.7.1.js" type="text/javascript"></script> </head> <body> <h1>This page does nothing....</h1> <script type="text/javascript"> var json3 = { "count": 2, "items": [{ "title": "Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)", "description": "Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China’s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store’s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone", "link": "http://wik.io/info/US/309201303", "timestamp": 1326439500, "image": null, "embed": null, "language": null, "user": null, "user_image": null, "user_link": null, "user_id": null, "geo": null, "source": "wikio", "favicon": "http://wikio.com/favicon.ico", "type": "blogs", "domain": "wik.io", "id": "2388575404943858468" }, { "title": "Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)", "description": "SHANGHAI – Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone", "link": "http://wik.io/info/US/309198933", "timestamp": 1326439320, "image": null, "embed": null, "language": null, "user": null, "user_image": null, "user_link": null, "user_id": null, "geo": null, "source": "wikio", "favicon": "http://wikio.com/favicon.ico", "type": "blogs", "domain": "wik.io", "id": "16209851193593872066" } ] }; const items = json3.items const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here const header = Object.keys(items[0]) let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(',')) csv.unshift(header.join(',')) csv = csv.join('\r\n') var link = document.createElement("a"); link.id="lnkDwnldLnk"; document.body.appendChild(link); blob = new Blob([csv], { type: 'text/csv' }); var csvUrl = window.webkitURL.createObjectURL(blob); var filename = 'UserExport.csv'; jQuery("#lnkDwnldLnk") .attr({ 'download': filename, 'href': csvUrl }); jQuery('#lnkDwnldLnk')[0].click(); document.body.removeChild(link); </script> </body> </html>
sumber
Adaptasi dari jawaban praneybehl untuk bekerja dengan objek bertingkat dan pemisah tab
function ConvertToCSV(objArray) { let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray; if(!Array.isArray(array)) array = [array]; let str = ''; for (let i = 0; i < array.length; i++) { let line = ''; for (let index in array[i]) { if (line != '') line += ',' const item = array[i][index]; line += (typeof item === 'object' && item !== null ? ConvertToCSV(item) : item); } str += line + '\r\n'; } do{ str = str.replace(',','\t').replace('\t\t', '\t'); }while(str.includes(',') || str.includes('\t\t')); return str.replace(/(\r\n|\n|\r)/gm, ""); //removing line breaks: https://stackoverflow.com/a/10805198/4508758 }
sumber
Berikut adalah cara untuk melakukannya untuk objek dinamis dalam dengan cara berorientasi objek untuk versi js yang lebih baru. Anda mungkin harus mengubah jenis yang terpisah setelah wilayah.
private ConvertToCSV(objArray) { let rows = typeof objArray !== "object" ? JSON.parse(objArray) : objArray; let header = ""; Object.keys(rows[0]).map(pr => (header += pr + ";")); let str = ""; rows.forEach(row => { let line = ""; let columns = typeof row !== "object" ? JSON.parse(row) : Object.values(row); columns.forEach(column => { if (line !== "") { line += ";"; } if (typeof column === "object") { line += JSON.stringify(column); } else { line += column; } }); str += line + "\r\n"; }); return header + "\r\n" + str; }
sumber
Terkadang benda memiliki panjang yang berbeda. Jadi saya mengalami masalah yang sama dengan Kyle Pennell. Tetapi alih-alih mengurutkan array, kita hanya melewatinya dan memilih yang terpanjang. Kompleksitas waktu dikurangi menjadi O (n), dibandingkan dengan O (n log (n)) saat penyortiran pertama.
Saya mulai dengan kode dari versi ES6 (2016) Christian Landgren yang diperbarui .
json2csv(json) { // you can skip this step if your input is a proper array anyways: const simpleArray = JSON.parse(json) // in array look for the object with most keys to use as header const header = simpleArray.map((x) => Object.keys(x)) .reduce((acc, cur) => (acc.length > cur.length ? acc : cur), []); // specify how you want to handle null values here const replacer = (key, value) => ( value === undefined || value === null ? '' : value); let csv = simpleArray.map((row) => header.map( (fieldName) => JSON.stringify(row[fieldName], replacer)).join(',')); csv = [header.join(','), ...csv]; return csv.join('\r\n'); }
sumber
Saya ingin mengabaikan jawaban @Christian Landgren di atas. Saya bingung kenapa file CSV saya hanya 3 kolom / header. Ini karena elemen pertama di json saya hanya memiliki 3 kunci. Jadi, Anda perlu berhati-hati dengan
const header = Object.keys(json[0])
antrean. Ini mengasumsikan bahwa elemen pertama dalam array adalah representatif. Saya memiliki JSON yang berantakan dengan beberapa objek memiliki lebih atau kurang.Jadi saya menambahkan
array.sort
ini yang akan memesan JSON dengan jumlah kunci. Dengan begitu file CSV Anda akan memiliki jumlah kolom maksimal.Ini juga merupakan fungsi yang dapat Anda gunakan dalam kode Anda. Beri makan saja JSON!
function convertJSONtocsv(json) { if (json.length === 0) { return; } json.sort(function(a,b){ return Object.keys(b).length - Object.keys(a).length; }); const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here const header = Object.keys(json[0]) let csv = json.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(',')) csv.unshift(header.join(',')) csv = csv.join('\r\n') fs.writeFileSync('awesome.csv', csv) }
sumber
Inilah versi sederhana saya untuk mengonversi larik objek ito CSV (dengan asumsi semua objek itu memiliki atribut yang sama):
var csv = [] if (items.length) { var keys = Object.keys(items[0]) csv.push(keys.join(',')) items.forEach(item => { let vals = keys.map(key => item[key] || '') csv.push(vals.join(',')) }) } csv = csv.join('\n')
sumber
Tulis Csv.
function writeToCsv(dataToWrite, callback) { var dataToWrite; var fs = require('fs'); dataToWrite = convertToCSV(dataToWrite); fs.writeFile('assets/distanceInfo.csv', dataToWrite, 'utf8', function (err) { if (err) { console.log('Some error occured - file either not saved or corrupted file saved.'); } else{ console.log('It\'s saved!'); } callback("data_saved | assets/distanceInfo.csv") }); } function convertToCSV(objArray) { var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray; var str = ''; for (var i = 0; i < array.length; i++) { var line = ''; for (var index in array[i]) { if (line != '') line += ',' line += array[i][index]; } str += line + '\r\n'; } return str; }
sumber
Lucu tidak ada yang lengkap atau bekerja di sini (IE atau node.js). Jawab pertanyaan serupa, JSON sedikit terstruktur (misalkan tidak perlu disalin lagi), termasuk juga cuplikan demo. Konversi JSON Ke CSV (JavaScript): Cara memformat konversi CSV dengan benar Berharap tidak hanya konverter tipe tunggal, juga di Github saya (disebutkan dalam profil) serupa yang digunakan untuk menganalisis struktur JSON yang tidak diketahui. Saya penulis kode dalam jawaban ini dan semua kode di Github saya (kecuali beberapa proyek dimulai sebagai terjemahan fork / +).
sumber
Secara pribadi saya akan menggunakan perpustakaan d3-dsv untuk melakukan ini. Mengapa demikian
reinvent the wheel
?import { csvFormat } from 'd3-dsv'; /** * Based on input data convert it to csv formatted string * @param (Array) columnsToBeIncluded array of column names (strings) * which needs to be included in the formated csv * @param {Array} input array of object which need to be transformed to string */ export function convertDataToCSVFormatString(input, columnsToBeIncluded = []) { if (columnsToBeIncluded.length === 0) { return csvFormat(input); } return csvFormat(input, columnsToBeIncluded); }
Dengan pohon-gemetar Anda bisa mengimpor fungsi tertentu dari
d3-dsv
perpustakaansumber