How to convert JSON to CSV format and store in a variable
Ok I finally got this code working:
<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>
Thanks alot for all the support to all the contributors.
Praney
I want to convert Json file to csv file using Pyhton
In Python 3 the required syntax changed and the csv module now works with text mode 'w'
, but also needs the newline=''
(empty string) parameter to suppress Windows line translation.
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
writer = csv.writer(outfile)
Convert JSON to CSV using javascript
I assume you wanna use the keys as the header in CSV file.
What you need is to open a write stream, the format of the CSV file is pure strings with commas separating the values.
// ...
let mapped=filtered.map((a)=>{
//...
})
// ...
const fs = require('fs');
let writeStream = fs.createWriteStream('./output.csv');
writeStream.on('open', () => {
// get the header
const header = Object.keys(mapped[0]).toString().concat('\n');
writeStream.write(header);
mapped.forEach((obj) => {
const values = Object.values(obj).toString().concat('\n');
writeStream.write(values);
});
writeStream.end();
});
How to convert JSON to CSV and then save to computer as CSV file
You are probably not starting the promises, and it looks like you are not using the json2csv correctly.
Take a look at this example:
let json2csv = require("json2csv");
let fs = require("fs");
apiDataPull = Promise.resolve([
{
'day': '*date*',
'revenue': '*revenue value*'
}]).then(data => {
return json2csv.parseAsync(data, {fields: ['day', 'revenue', 'totalImpressions', 'eCPM']})
}).then(csv => {
fs.writeFile('pubmaticData.csv', csv, function (err) {
if (err) throw err;
console.log('File Saved!')
});
});
The saved file is:
"day","revenue","totalImpressions","eCPM"
"*date*","*revenue value*",,
How to convert JSON data to CSV format on the fly with out using csv file
If you can already convert the json into csv, then just append the output strings together assigned to a string variable instead of writing it to a file. Or am I misunderstanding what you want?
Instead of:
fwrite($f, "$outputString\n");
you can put:
$csv .= $outputString;
And finish it with:
$array = explode("\n", $csv);
Related Topics
React Native - Image Require Module Using Dynamic Names
How to Group by and Sum an Array of Objects
Differencebetween a User and a Guildmember in Discord.Js
How to Debug JavaScript/Jquery Event Bindings with Firebug or Similar Tools
Can't Bind to 'Ngmodel' Since It Isn't a Known Property of 'Input'
How to Remove All Line Breaks from a String
How to Determine User's Locale Within Browser
Extract Hostname Name from String
JavaScript Before Leaving the Page
How to Escape Regular Expression Special Characters Using JavaScript
Differencebetween String Primitives and String Objects in JavaScript
How Does JavaScript's Sort() Work
How to Send a Variable Number of Arguments to a JavaScript Function
Does IE9 Support Console.Log, and Is It a Real Function
How to Access Svg Elements with JavaScript
What's the Significant Use of Unary Plus and Minus Operators
How Does Facebook Disable the Browser's Integrated Developer Tools