How to Convert JSON to CSV Format and Store in a Variable

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



Leave a reply



Submit