- I am trying to convert JSON to CSV, I referred Converting JSON File to CSV with JavaScript, and How to export JavaScript array info to csv (on client side)?
- As my data is nested under
Rows
it is bringing the JSON in single-single character lines. - Sample JSON
- Expected Output
UPDATE
- I am receiving a
base 64 string
sample - Then decoding the
base-64
as below
let jsonContent = atob(base_64_string);
CodePudding user response:
This could help you. The headers are the ones from the json input at the moment, but if you desire the ones in your csv output example you can easily swap them.
//Added after discussion: It shows you how to prepare your base-64 string
//transform base 64 string in a decoded string
let decoded_string = atob(base_64_string);
let jsonString = JSON.parse(decoded_string);
//Example data - uncomment if you instead immediately paste the json object
//let jsonString = <redacted>;//redacted for brevity, but just paste your json file here if you want an example
//Select our data from the raw object
var data = JSON.parse(jsonString.Rows);
//Desired headers in the .csv. Other fields are ignored
let headers = ["Transaction_Date","Particulars","Amount",'Cr_Dr', "Balance", "Transaction_Type","Normalized_Party_Name_Label", "Normalized_Charge_Name_Label", "Charge_Class"]
//Choose your seperator
const seperator = ",";
//Prepare csv with a header row and our data
const csv = [headers.join(seperator),
...data.map(row => headers.map(field => `${row[field]}`).join(seperator))
]
//Export our csv in rows to a csv file
let csvContent = "data:text/csv;charset=utf-8,"
csv.join("\n");
var encodedUri = encodeURI(csvContent);
window.open(encodedUri);
working playcode example:
CodePudding user response:
This may help you
<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>