I tried to convert dynamic JSON to CSV, I investigate libs and answers I can't find a remarkable thing.
This and this examples could be helpful but I can't add the JSON's struct to my code, JSON is dynamic.
In Python & JS, I saw these examples;
Python;
# Python program to convert
# JSON file to CSV
import json
import csv
# Opening JSON file and loading the data
# into the variable data
with open('data.json') as json_file:
data = json.load(json_file)
employee_data = data['emp_details']
# now we will open a file for writing
data_file = open('data_file.csv', 'w')
# create the csv writer object
csv_writer = csv.writer(data_file)
# Counter variable used for writing
# headers to the CSV file
count = 0
for emp in employee_data:
if count == 0:
# Writing headers of CSV file
header = emp.keys()
csv_writer.writerow(header)
count += 1
# Writing data of CSV file
csv_writer.writerow(emp.values())
data_file.close()
JS;
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])
const csv = [
header.join(','), // header row first
...items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
].join('\r\n')
console.log(csv)
These codes help convert dynamic JSON to CSV easily.
Example input & output;
JSON(input);
[
{
"name": "John",
"age": "21"
},
{
"name": "Noah",
"age": "23"
},
{
"name": "Justin",
"age": "25"
}
]
CSV(output);
"name","age"
"John","21"
"Noah","23"
"Justi","25"
So how can I convert dynamic JSON to CSV in Go?
PS: I discover a Golang lib(json2csv) that helps to convert but only works on command prompt.
I few online tools for example;
json2csvcan do this for you, so what's your question?