This is common thing now a days we have all data in JSON and when we have to sent it as a csv file we need to convert. Following code found stackoverflow.com, and credit goes to developer. I am putting into my blog for easy access and reference to my blog reader.
//logData is the JSON object having json data, rest of the code do the job.
const items = logData
const replacer = (key, value) => value === null ? '' : value
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)
//logData is the JSON object having json data, rest of the code do the job.
const items = logData
const replacer = (key, value) => value === null ? '' : value
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)
No comments:
Post a Comment
Your feedback is always appreciated. I will try to reply to your queries as soon as time allows.Please don't spam,spam comments will be deleted upon reviews.