Answers for "json to csv python"

3

json to csv

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);
Posted by: Guest on March-02-2022
4

json to csv

# call csvkit (which is a Python tool) to convert json to csv:
# https://csvkit.readthedocs.io/en/latest/

in2csv data.json > data.csv
Posted by: Guest on April-14-2021
0

csv to json python

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 DictReader
    with open(csvFilePath, encoding='utf-8') as csvf:
        csvReader = csv.DictReader(csvf)
         
        # Convert each row into a dictionary
        # and add it to data
        for rows in csvReader:
             
            # 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
    with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
        jsonf.write(json.dumps(data, indent=4))
         
# Driver Code
 
# Decide the two file paths according to your
# computer system
csvFilePath = r'Names.csv'
jsonFilePath = r'Names.json'
 
# Call the make_json function
make_json(csvFilePath, jsonFilePath)
Posted by: Guest on February-10-2022

Python Answers by Framework

Browse Popular Code Answers by Language