import pandas as pd
# enter the json filename to be converted to json
JSON_FILE='json_filename.json'
# enter the csv filename you wish to save it asCSV_FILE='csv_filename.csv'withopen(JSON_FILE, encoding ='utf-8')asf:
df = pd.read_json(f)
df.to_csv(CSV_FILE, encoding ='utf-8', index =False)
import csv
import json
# Function to convert a CSV to JSON
# Takes the file paths as arguments
def make_json(csvFilePath, jsonFilePath):
# create a dictionary
data ={}
# Open a csv reader called DictReaderwithopen(csvFilePath, encoding='utf-8')ascsvf:
csvReader = csv.DictReader(csvf)
# Convert each row into a dictionary
# and add it to data
for rows incsvReader:
# Assuming a column named 'No' to
# be the primary key
key = rows['No']
data[key]= rows
# Open a json writer, and use the json.dumps()
# function to dump data
withopen(jsonFilePath,'w', encoding='utf-8')asjsonf:
jsonf.write(json.dumps(data, indent=4))
# DriverCode
# Decide the two file paths according to your
# computer system
csvFilePath = r'Names.csv'
jsonFilePath = r'Names.json'
# Call the make_json functionmake_json(csvFilePath, jsonFilePath)
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"}]}];functiontoCsv(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 arrayconst 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("
");console.log(csvString);return csvString;}//TESTtoCsv(myObj);