Home > Back-end >  Problem in converting csv to json in python
Problem in converting csv to json in python

Time:01-08

I am trying to convert csv file to json in python and i have an issue where in one column data has a comma but it is enclosed in double quotes. When considering it as a csv file, data is loading properly without any issues. But while converting to json it is failing saying "Too few arguments passed".

sample Data:

col1,col2,col3

apple,Fruit,good for health

banana,Fruit,"good for weight gain , good for calcium"

Brinjal,Vegetable,good for skin

while converting the above file to json, it is failed considering 2nd row has 4 columns.

Error statement: pandas.errors.ParserError: Too many columns specified: expected 3 and found 4

data=pd.read_csv(sampledata.csv,header=None)
data_json = json.loads(data.to_json(orient='records'))
with open(filename.json,'w',encoding='utf-8')as jsonf:
     jsonf.write(json.dumps(data_json,indent=4))

CodePudding user response:

This works:

df = pd.read_csv("test.csv")
df_json = df.to_json() 
  •  Tags:  
  • Related