xxxxxxxxxx
import csv
import json
csv_file = 'path/to/input.csv'
json_file = 'path/to/output.json'
data = []
# Read CSV file and parse rows into a list of dictionaries
with open(csv_file, 'r') as file:
reader = csv.DictReader(file)
for row in reader:
data.append(row)
# Write JSON data to file
with open(json_file, 'w') as file:
json.dump(data, file, indent=4)
xxxxxxxxxx
import pandas as pd
df = pd.read_json (r'input.json')
df.to_csv (r'output.csv', index = None)
xxxxxxxxxx
let myObj= [
{ "ean":1, "name":'prod1', "attibutes":[{"attr": 100,"color": "green"},{"attr": 200,"color": "red"}] },
{ "ean":2, "name":'prod1', "attibutes":[{"attr": 100,"color": "white"},{"attr": 200,"color": "blu"}] }
];
function toCsv(arrOfObj){
// array of objects with nested objects
// keys for arr of obj (rows) is numeric
// key for elements of nested obj is a name
// I transform each row in an array
const csvString = [
arrOfObj.map(item => [
item.ean,
item.name,
//NO: passes 0:object,1:obj, Object.entries(item.attibutes).map(([k,v]) => `${k}:${v}`)
Object.keys(item.attibutes).map(row => [ Object.keys(item.attibutes[row]).map( elkey => elkey + ':' + item.attibutes[row][elkey] )])
])]
.map(e => e.join(";"))
.join("\n");
console.log(csvString);
return csvString;
}
//TEST
toCsv(myObj);
xxxxxxxxxx
# call csvkit (which is a Python tool) to convert json to csv:
# https://csvkit.readthedocs.io/en/latest/
in2csv data.json > data.csv
xxxxxxxxxx
const items = [
{name: 'John', age: 31},
{name: 'Maria', age: 25},
];
const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
const header = Object.keys(items[0]);
let csv = items.map(row => header.map(fieldName => row[fieldName], replacer).join(','));
csv.unshift(header.join(','));
csv = csv.join('\r\n');
console.log(csv)
xxxxxxxxxx
import json
if __name__ == '__main__':
try:
with open('input.json', 'r') as f:
data = json.loads(f.read())
output = ','.join([*data[0]])
for obj in data:
output += f'\n{obj["Name"]},{obj["age"]},{obj["birthyear"]}'
with open('output.csv', 'w') as f:
f.write(output)
except Exception as ex:
print(f'Error: {str(ex)}')
This trick is a modification of this popular recipe to convert CSV files to the JSON format:
xxxxxxxxxx
$ python3 -c \
"import csv,json,sys;print(json.dumps(list(csv.reader(open(sys.argv[1])))))" \
covid19-vaccinations-town-age-grp.csv