How can i convert CSV in JSON like I want

Question:

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

Asked By: MY.D

||

Answers:

You can convert here:
https://csvjson.com/csv2json
And here is how to do it in Python:
https://www.askpython.com/python/examples/convert-csv-to-json

Answered By: Bummbumm6

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
df = pd.read_csv(filename)
df.to_dict()
Answered By: gittert

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"
  }
]
Answered By: Fred

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)
Answered By: Harith
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.