Home > Back-end >  How can i convert CSV in JSON like I want
How can i convert CSV in JSON like I want

Time:12-21

Hello I show you my problem's :

I right that for convert my csv in Json. But the résult is not exactly what I Want .

main.py

import csv
 
filename ="forcebrute.csv"
 
# opening the file using "with"
# statement
with open(filename, 'r') as data:
  for line in csv.DictReader(data):
      print(line)

csv

name;price;profit

Action-1;20;5

Action-2;30;10

Action-3;50;15

Action-4;70;20

Action-5;60;17

result i have:

{'name;price;profit': 'Action-1;20;5'}

{'name;price;profit': 'Action-2;30;10'}

{'name;price;profit': 'Action-3;50;15'}

{'name;price;profit': 'Action-4;70;20'}

{'name;price;profit': 'Action-5;60;17'}

And I would like this result:

enter image description here

CodePudding user response:

You will need to specify the column delimiter then you can use json.dumps() to give you the required output format

import csv
import json

with open('forcebrute.csv') as data:
    print(json.dumps([d for d in csv.DictReader(data, delimiter=';')], indent=2))

Output:

[
  {
    "name": "Action-1",
    "price": "20",
    "profit": "5"
  },
  {
    "name": "Action-2",
    "price": "30",
    "profit": "10"
  },
  {
    "name": "Action-3",
    "price": "50",
    "profit": "15"
  },
  {
    "name": "Action-4",
    "price": "70",
    "profit": "20"
  },
  {
    "name": "Action-5",
    "price": "60",
    "profit": "17"
  }
]

CodePudding user response:

You will need to use Dictreader from the csv library to read the contents of the CSV file and then convert the contents to a list before using json.dumps to turn the data into JSON.

import csv
import json

filename ="forcebrute.csv"

# Open the CSV file and read the contents into a list of dictionaries
with open(filename, 'r') as f:
   reader = csv.DictReader(f, delimiter=';')
   csv_data = list(reader)

# Convert the data to a JSON string and print it to the console
json_data = json.dumps(csv_data)
print(json_data)

CodePudding user response:

An easy approach would be using pandas, also quite fast with large csv files. It might need some tweaking but you get the point.

import pandas as pd
import json

df = pd.read_csv(filename, sep = ';')
data = json.dumps(df.to_dict('records'))
  • Related